How to configure Spring Security with Hibernate and XML Announcing the arrival of Valued Associate #679: Cesar Manara Planned maintenance scheduled April 23, 2019 at 23:30 UTC (7:30pm US/Eastern) Data science time! April 2019 and salary with experience The Ask Question Wizard is Live!How do you parse and process HTML/XML in PHP?What's the difference between @Component, @Repository & @Service annotations in Spring?How do I POST JSON data with Curl from a terminal/commandline to Test Spring REST?Spring Security with Openid and Database IntegrationSpring MVC + Hibernate 4 + Spring SecurityError in spring-security.xml “ Configuration problem: spring-security-web classes are not available. You need these to use <filter- chain-map>”spring security UserDetailsService implementation and security userdetails.User not authenticatingSpring security with user XML configuration does not workSpring Security: LDAP AuthenticationUserDetailsService is not invoked in spring security
Did pre-Columbian Americans know the spherical shape of the Earth?
Why did Bronn offer to be Tyrion Lannister's champion in trial by combat?
Twin's vs. Twins'
Why does BitLocker not use RSA?
Is a copyright notice with a non-existent name be invalid?
Inverse square law not accurate for non-point masses?
Is there any significance to the prison numbers of the Beagle Boys starting with 176-?
Is Mordenkainens' Sword under powered?
How to make triangles with rounded sides and corners? (squircle with 3 sides)
When to apply negative sign when number is squared
Can the Haste spell grant both a Beast Master ranger and their animal companion extra attacks?
Order between one to one functions and their inverses
systemd and copy (/bin/cp): no such file or directory
Why can't fire hurt Daenerys but it did to Jon Snow in season 1?
Why not use the yoke to control yaw, as well as pitch and roll?
Random body shuffle every night—can we still function?
My mentor says to set image to Fine instead of RAW — how is this different from JPG?
Is there a spell that can create a permanent fire?
Sally's older brother
Weaponising the Grasp-at-a-Distance spell
How to ask rejected full-time candidates to apply to teach individual courses?
Derived column in a data extension
Did John Wesley plagiarize Matthew Henry...?
Marquee sign letters
How to configure Spring Security with Hibernate and XML
Announcing the arrival of Valued Associate #679: Cesar Manara
Planned maintenance scheduled April 23, 2019 at 23:30 UTC (7:30pm US/Eastern)
Data science time! April 2019 and salary with experience
The Ask Question Wizard is Live!How do you parse and process HTML/XML in PHP?What's the difference between @Component, @Repository & @Service annotations in Spring?How do I POST JSON data with Curl from a terminal/commandline to Test Spring REST?Spring Security with Openid and Database IntegrationSpring MVC + Hibernate 4 + Spring SecurityError in spring-security.xml “ Configuration problem: spring-security-web classes are not available. You need these to use <filter- chain-map>”spring security UserDetailsService implementation and security userdetails.User not authenticatingSpring security with user XML configuration does not workSpring Security: LDAP AuthenticationUserDetailsService is not invoked in spring security
.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty height:90px;width:728px;box-sizing:border-box;
I have configured Spring Security in my project and works as expected, hiding a specific page, when using the default form. But when I create my own login form, the users have not roles, so the page is still hidden, as I configured the XML to show the page only to authenticated users.
I have one entity class (Administrators) with id, username, password, role attributes (I do not want to use a second table 'roles' for now).
I have read many tutorials, others suggesting that the entity class should implement UserDetails or creating a MyUserDetailsService that implements UserDetailsService. Why would I need to do that?
Anyway, I tried everything I read but got no results. The protected page is still hidden, even if I login. All I want is Administrators that login, to have a ROLE_ADMIN (or ROLE_MODERATOR, as these are the only options they can select when they register) so they will be able to access the protected page (/admin/list).
I have studied this link Spring Security+Hibernate+XML
and from what I understand I have to change these lines in spring-security.xml as in the following code:
<authentication-manager>
<authentication-provider user-service-ref="myUserDetailsService" >
</authentication-provider>
</authentication-manager>
So how would I create a new implementation of the UserDetailsService when I have just one table of Administrators and all I want is to have their roles granted upon login?
Thank you.
Administrator class
@Entity
@Table(name="administrator")
public class Administrator {
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
@Column(name="administrator_id")
private int id;
@NotNull(message="is required")
@Size(min=6, message="minimum chars 6")
@Size(max=45, message="maximum chars 45")
@Column(name="username")
private String username;
@NotNull(message="is required")
@Size(min=6, message="minimum chars 6")
@Size(max=45, message="maximum chars 45")
@Column(name="password")
private String password;
@Column(name="role")
private String role;
// Class constructor
public Administrator()
// Getters and setters
public int getId()
return id;
public void setId(int id)
this.id = id;
public String getUsername()
return username;
public void setUsername(String username)
this.username = username;
public String getPassword()
return password;
public void setPassword(String password)
this.password = password;
public String getRole()
return role;
public void setRole(String role)
this.role = role;
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID"
version="3.1">
<display-name>platform</display-name>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
<welcome-file>index.html</welcome-file>
</welcome-file-list>
<!-- Listener for multiple xml configuration files -->
<listener>
<listener-
class>org.springframework.web.context.ContextLoaderListener</listener-
class>
</listener>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
/WEB-INF/platform-servlet.xml,
/WEB-INF/spring-security.xml
</param-value>
</context-param>
<servlet>
<servlet-name>dispatcher</servlet-name>
<servlet-
class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value></param-value>
</init-param>
<load-on-startup>1</load-on-startup>
<!-- Turn on async support for servlet -->
<async-supported>true</async-supported>
</servlet>
<servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<!-- Add filter for Spring security mapping -->
<filter>
<filter-name>springSecurityFilterChain</filter-name>
<filter-
class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
</filter>
<filter-mapping>
<filter-name>springSecurityFilterChain</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
spring-security.xml
<beans:beans xmlns="http://www.springframework.org/schema/security"
xmlns:beans="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/security
http://www.springframework.org/schema/security/spring-security.xsd">
<http auto-config="true" use-expressions="true">
<!-- <intercept-url pattern="/admin/list" access="hasRole('ROLE_ADMIN')" /> -->
<intercept-url pattern="/home/login-page" access="isAnonymous()" />
<intercept-url pattern="/admin/list" access="isAuthenticated()" />
<form-login
login-page="/home/login-page"
default-target-url="/home/main"
authentication-failure-url="/home/login-page"
login-processing-url="/login-process" />
<logout logout-success-url="/home/login-page"/>
</http>
<authentication-manager>
<authentication-provider>
<user-service>
<user name="user111" password="pass111" authorities="ROLE_USER" />
</user-service>
</authentication-provider>
</authentication-manager>
</beans:beans>
xml spring hibernate spring-mvc spring-security
add a comment |
I have configured Spring Security in my project and works as expected, hiding a specific page, when using the default form. But when I create my own login form, the users have not roles, so the page is still hidden, as I configured the XML to show the page only to authenticated users.
I have one entity class (Administrators) with id, username, password, role attributes (I do not want to use a second table 'roles' for now).
I have read many tutorials, others suggesting that the entity class should implement UserDetails or creating a MyUserDetailsService that implements UserDetailsService. Why would I need to do that?
Anyway, I tried everything I read but got no results. The protected page is still hidden, even if I login. All I want is Administrators that login, to have a ROLE_ADMIN (or ROLE_MODERATOR, as these are the only options they can select when they register) so they will be able to access the protected page (/admin/list).
I have studied this link Spring Security+Hibernate+XML
and from what I understand I have to change these lines in spring-security.xml as in the following code:
<authentication-manager>
<authentication-provider user-service-ref="myUserDetailsService" >
</authentication-provider>
</authentication-manager>
So how would I create a new implementation of the UserDetailsService when I have just one table of Administrators and all I want is to have their roles granted upon login?
Thank you.
Administrator class
@Entity
@Table(name="administrator")
public class Administrator {
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
@Column(name="administrator_id")
private int id;
@NotNull(message="is required")
@Size(min=6, message="minimum chars 6")
@Size(max=45, message="maximum chars 45")
@Column(name="username")
private String username;
@NotNull(message="is required")
@Size(min=6, message="minimum chars 6")
@Size(max=45, message="maximum chars 45")
@Column(name="password")
private String password;
@Column(name="role")
private String role;
// Class constructor
public Administrator()
// Getters and setters
public int getId()
return id;
public void setId(int id)
this.id = id;
public String getUsername()
return username;
public void setUsername(String username)
this.username = username;
public String getPassword()
return password;
public void setPassword(String password)
this.password = password;
public String getRole()
return role;
public void setRole(String role)
this.role = role;
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID"
version="3.1">
<display-name>platform</display-name>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
<welcome-file>index.html</welcome-file>
</welcome-file-list>
<!-- Listener for multiple xml configuration files -->
<listener>
<listener-
class>org.springframework.web.context.ContextLoaderListener</listener-
class>
</listener>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
/WEB-INF/platform-servlet.xml,
/WEB-INF/spring-security.xml
</param-value>
</context-param>
<servlet>
<servlet-name>dispatcher</servlet-name>
<servlet-
class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value></param-value>
</init-param>
<load-on-startup>1</load-on-startup>
<!-- Turn on async support for servlet -->
<async-supported>true</async-supported>
</servlet>
<servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<!-- Add filter for Spring security mapping -->
<filter>
<filter-name>springSecurityFilterChain</filter-name>
<filter-
class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
</filter>
<filter-mapping>
<filter-name>springSecurityFilterChain</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
spring-security.xml
<beans:beans xmlns="http://www.springframework.org/schema/security"
xmlns:beans="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/security
http://www.springframework.org/schema/security/spring-security.xsd">
<http auto-config="true" use-expressions="true">
<!-- <intercept-url pattern="/admin/list" access="hasRole('ROLE_ADMIN')" /> -->
<intercept-url pattern="/home/login-page" access="isAnonymous()" />
<intercept-url pattern="/admin/list" access="isAuthenticated()" />
<form-login
login-page="/home/login-page"
default-target-url="/home/main"
authentication-failure-url="/home/login-page"
login-processing-url="/login-process" />
<logout logout-success-url="/home/login-page"/>
</http>
<authentication-manager>
<authentication-provider>
<user-service>
<user name="user111" password="pass111" authorities="ROLE_USER" />
</user-service>
</authentication-provider>
</authentication-manager>
</beans:beans>
xml spring hibernate spring-mvc spring-security
The UserDetailsService interface is used to retrieve user-related data. It has one method named loadUserByUsername() which finds a user entity based on the username and can be overridden to customize the process of finding the user. Please check link baeldung.com/spring-security-authentication-with-a-database
– Amit K Bist
Aug 23 '17 at 2:52
add a comment |
I have configured Spring Security in my project and works as expected, hiding a specific page, when using the default form. But when I create my own login form, the users have not roles, so the page is still hidden, as I configured the XML to show the page only to authenticated users.
I have one entity class (Administrators) with id, username, password, role attributes (I do not want to use a second table 'roles' for now).
I have read many tutorials, others suggesting that the entity class should implement UserDetails or creating a MyUserDetailsService that implements UserDetailsService. Why would I need to do that?
Anyway, I tried everything I read but got no results. The protected page is still hidden, even if I login. All I want is Administrators that login, to have a ROLE_ADMIN (or ROLE_MODERATOR, as these are the only options they can select when they register) so they will be able to access the protected page (/admin/list).
I have studied this link Spring Security+Hibernate+XML
and from what I understand I have to change these lines in spring-security.xml as in the following code:
<authentication-manager>
<authentication-provider user-service-ref="myUserDetailsService" >
</authentication-provider>
</authentication-manager>
So how would I create a new implementation of the UserDetailsService when I have just one table of Administrators and all I want is to have their roles granted upon login?
Thank you.
Administrator class
@Entity
@Table(name="administrator")
public class Administrator {
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
@Column(name="administrator_id")
private int id;
@NotNull(message="is required")
@Size(min=6, message="minimum chars 6")
@Size(max=45, message="maximum chars 45")
@Column(name="username")
private String username;
@NotNull(message="is required")
@Size(min=6, message="minimum chars 6")
@Size(max=45, message="maximum chars 45")
@Column(name="password")
private String password;
@Column(name="role")
private String role;
// Class constructor
public Administrator()
// Getters and setters
public int getId()
return id;
public void setId(int id)
this.id = id;
public String getUsername()
return username;
public void setUsername(String username)
this.username = username;
public String getPassword()
return password;
public void setPassword(String password)
this.password = password;
public String getRole()
return role;
public void setRole(String role)
this.role = role;
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID"
version="3.1">
<display-name>platform</display-name>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
<welcome-file>index.html</welcome-file>
</welcome-file-list>
<!-- Listener for multiple xml configuration files -->
<listener>
<listener-
class>org.springframework.web.context.ContextLoaderListener</listener-
class>
</listener>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
/WEB-INF/platform-servlet.xml,
/WEB-INF/spring-security.xml
</param-value>
</context-param>
<servlet>
<servlet-name>dispatcher</servlet-name>
<servlet-
class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value></param-value>
</init-param>
<load-on-startup>1</load-on-startup>
<!-- Turn on async support for servlet -->
<async-supported>true</async-supported>
</servlet>
<servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<!-- Add filter for Spring security mapping -->
<filter>
<filter-name>springSecurityFilterChain</filter-name>
<filter-
class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
</filter>
<filter-mapping>
<filter-name>springSecurityFilterChain</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
spring-security.xml
<beans:beans xmlns="http://www.springframework.org/schema/security"
xmlns:beans="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/security
http://www.springframework.org/schema/security/spring-security.xsd">
<http auto-config="true" use-expressions="true">
<!-- <intercept-url pattern="/admin/list" access="hasRole('ROLE_ADMIN')" /> -->
<intercept-url pattern="/home/login-page" access="isAnonymous()" />
<intercept-url pattern="/admin/list" access="isAuthenticated()" />
<form-login
login-page="/home/login-page"
default-target-url="/home/main"
authentication-failure-url="/home/login-page"
login-processing-url="/login-process" />
<logout logout-success-url="/home/login-page"/>
</http>
<authentication-manager>
<authentication-provider>
<user-service>
<user name="user111" password="pass111" authorities="ROLE_USER" />
</user-service>
</authentication-provider>
</authentication-manager>
</beans:beans>
xml spring hibernate spring-mvc spring-security
I have configured Spring Security in my project and works as expected, hiding a specific page, when using the default form. But when I create my own login form, the users have not roles, so the page is still hidden, as I configured the XML to show the page only to authenticated users.
I have one entity class (Administrators) with id, username, password, role attributes (I do not want to use a second table 'roles' for now).
I have read many tutorials, others suggesting that the entity class should implement UserDetails or creating a MyUserDetailsService that implements UserDetailsService. Why would I need to do that?
Anyway, I tried everything I read but got no results. The protected page is still hidden, even if I login. All I want is Administrators that login, to have a ROLE_ADMIN (or ROLE_MODERATOR, as these are the only options they can select when they register) so they will be able to access the protected page (/admin/list).
I have studied this link Spring Security+Hibernate+XML
and from what I understand I have to change these lines in spring-security.xml as in the following code:
<authentication-manager>
<authentication-provider user-service-ref="myUserDetailsService" >
</authentication-provider>
</authentication-manager>
So how would I create a new implementation of the UserDetailsService when I have just one table of Administrators and all I want is to have their roles granted upon login?
Thank you.
Administrator class
@Entity
@Table(name="administrator")
public class Administrator {
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
@Column(name="administrator_id")
private int id;
@NotNull(message="is required")
@Size(min=6, message="minimum chars 6")
@Size(max=45, message="maximum chars 45")
@Column(name="username")
private String username;
@NotNull(message="is required")
@Size(min=6, message="minimum chars 6")
@Size(max=45, message="maximum chars 45")
@Column(name="password")
private String password;
@Column(name="role")
private String role;
// Class constructor
public Administrator()
// Getters and setters
public int getId()
return id;
public void setId(int id)
this.id = id;
public String getUsername()
return username;
public void setUsername(String username)
this.username = username;
public String getPassword()
return password;
public void setPassword(String password)
this.password = password;
public String getRole()
return role;
public void setRole(String role)
this.role = role;
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID"
version="3.1">
<display-name>platform</display-name>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
<welcome-file>index.html</welcome-file>
</welcome-file-list>
<!-- Listener for multiple xml configuration files -->
<listener>
<listener-
class>org.springframework.web.context.ContextLoaderListener</listener-
class>
</listener>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
/WEB-INF/platform-servlet.xml,
/WEB-INF/spring-security.xml
</param-value>
</context-param>
<servlet>
<servlet-name>dispatcher</servlet-name>
<servlet-
class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value></param-value>
</init-param>
<load-on-startup>1</load-on-startup>
<!-- Turn on async support for servlet -->
<async-supported>true</async-supported>
</servlet>
<servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<!-- Add filter for Spring security mapping -->
<filter>
<filter-name>springSecurityFilterChain</filter-name>
<filter-
class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
</filter>
<filter-mapping>
<filter-name>springSecurityFilterChain</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
spring-security.xml
<beans:beans xmlns="http://www.springframework.org/schema/security"
xmlns:beans="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/security
http://www.springframework.org/schema/security/spring-security.xsd">
<http auto-config="true" use-expressions="true">
<!-- <intercept-url pattern="/admin/list" access="hasRole('ROLE_ADMIN')" /> -->
<intercept-url pattern="/home/login-page" access="isAnonymous()" />
<intercept-url pattern="/admin/list" access="isAuthenticated()" />
<form-login
login-page="/home/login-page"
default-target-url="/home/main"
authentication-failure-url="/home/login-page"
login-processing-url="/login-process" />
<logout logout-success-url="/home/login-page"/>
</http>
<authentication-manager>
<authentication-provider>
<user-service>
<user name="user111" password="pass111" authorities="ROLE_USER" />
</user-service>
</authentication-provider>
</authentication-manager>
</beans:beans>
xml spring hibernate spring-mvc spring-security
xml spring hibernate spring-mvc spring-security
asked Aug 22 '17 at 21:34
IoannisGkIoannisGk
83
83
The UserDetailsService interface is used to retrieve user-related data. It has one method named loadUserByUsername() which finds a user entity based on the username and can be overridden to customize the process of finding the user. Please check link baeldung.com/spring-security-authentication-with-a-database
– Amit K Bist
Aug 23 '17 at 2:52
add a comment |
The UserDetailsService interface is used to retrieve user-related data. It has one method named loadUserByUsername() which finds a user entity based on the username and can be overridden to customize the process of finding the user. Please check link baeldung.com/spring-security-authentication-with-a-database
– Amit K Bist
Aug 23 '17 at 2:52
The UserDetailsService interface is used to retrieve user-related data. It has one method named loadUserByUsername() which finds a user entity based on the username and can be overridden to customize the process of finding the user. Please check link baeldung.com/spring-security-authentication-with-a-database
– Amit K Bist
Aug 23 '17 at 2:52
The UserDetailsService interface is used to retrieve user-related data. It has one method named loadUserByUsername() which finds a user entity based on the username and can be overridden to customize the process of finding the user. Please check link baeldung.com/spring-security-authentication-with-a-database
– Amit K Bist
Aug 23 '17 at 2:52
add a comment |
2 Answers
2
active
oldest
votes
First, you do not need to add an “authentication-manager” to your web.xml file. You have to create a SecurityConfiguration class that extends WebSecurityConfigurerAdapter. From there you can create the InMemoryUserDetailsManager bean as you see here:
// Bean that holds all authenticated users + new ones during runtime
@Bean
public InMemoryUserDetailsManager inMemoryUserDetailsManager()
final Properties users = new Properties();
// Get all administrators from the service
List<Administrator> theAdministrators = administratorService.getAdministrators();
// Iterate list and save current username, password and role
for (int i = 0; i < theAdministrators.size(); i++)
// Get current attributes from administrator object
String currentUsername = theAdministrators.get(i).getUsername();
String encryptedPassword = theAdministrators.get(i).getPassword();
String currentRole = theAdministrators.get(i).getRole();
// Decrypt current password
String currentPassword = strongTextEncryptorHelper.decryptPassword(encryptedPassword);
// Authenticate all administrators in memory and grant them their roles
users.put(currentUsername, currentPassword + ", " + "ROLE_" + currentRole + ", " + "enabled");
// Return authenticated users + new ones during runtime
return new InMemoryUserDetailsManager(users);
@Autowired
public void configureGlobalSecurity(AuthenticationManagerBuilder auth) throws Exception
// Authenticate administrators in memory, with user details service
auth.userDetailsService(inMemoryUserDetailsManager());
Then, you can protect specific pages of your webapp by adding the path to the appropriate antMatchers() method:
protected void configure(HttpSecurity http) throws Exception
// Make login page and oauth token accessible without authentication
// Protect all pages and allow only admins and moderators to access them
http.csrf().disable()
.authorizeRequests()
.antMatchers("/home/login-page").permitAll()
.antMatchers("/oauth/token").permitAll()
.antMatchers("/home/**", "/admin/**"")
.access("hasAnyRole('ADMIN', 'MODERATOR')")
.and()
.formLogin()
.loginPage("/home/login-page")
.defaultSuccessUrl("/home/main", true)
.failureUrl("/home/login-page?fail=Invalid+login+details")
.and()
.logout().logoutSuccessUrl("/home/login-page")
.and()
.httpBasic().disable();
1
Thank you, I have just implemented it and it works!
– IoannisGk
Mar 1 at 21:50
add a comment |
There is one alternative, just make sure that the querys to retrieve the users and roles information are changed according to your db schema.
jdbc-authetnication
<authentication-manager>
<authentication-provider>
<jdbc-user-service data-source-ref="dataSource"
users-by-username-query=
"select username,password, enabled from users where username=?"
authorities-by-username-query=
"select username, role from user_roles where username =? " />
</authentication-provider>
</authentication-manager>
and the datasource is a bean
<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://localhost:3306/mydb" />
<property name="username" value="root" />
<property name="password" value="password" />
</bean>
here is a good example: http://www.mkyong.com/spring-security/spring-security-form-login-using-database/
add a comment |
Your Answer
StackExchange.ifUsing("editor", function ()
StackExchange.using("externalEditor", function ()
StackExchange.using("snippets", function ()
StackExchange.snippets.init();
);
);
, "code-snippets");
StackExchange.ready(function()
var channelOptions =
tags: "".split(" "),
id: "1"
;
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function()
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled)
StackExchange.using("snippets", function()
createEditor();
);
else
createEditor();
);
function createEditor()
StackExchange.prepareEditor(
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader:
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
,
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
);
);
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f45827327%2fhow-to-configure-spring-security-with-hibernate-and-xml%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
2 Answers
2
active
oldest
votes
2 Answers
2
active
oldest
votes
active
oldest
votes
active
oldest
votes
First, you do not need to add an “authentication-manager” to your web.xml file. You have to create a SecurityConfiguration class that extends WebSecurityConfigurerAdapter. From there you can create the InMemoryUserDetailsManager bean as you see here:
// Bean that holds all authenticated users + new ones during runtime
@Bean
public InMemoryUserDetailsManager inMemoryUserDetailsManager()
final Properties users = new Properties();
// Get all administrators from the service
List<Administrator> theAdministrators = administratorService.getAdministrators();
// Iterate list and save current username, password and role
for (int i = 0; i < theAdministrators.size(); i++)
// Get current attributes from administrator object
String currentUsername = theAdministrators.get(i).getUsername();
String encryptedPassword = theAdministrators.get(i).getPassword();
String currentRole = theAdministrators.get(i).getRole();
// Decrypt current password
String currentPassword = strongTextEncryptorHelper.decryptPassword(encryptedPassword);
// Authenticate all administrators in memory and grant them their roles
users.put(currentUsername, currentPassword + ", " + "ROLE_" + currentRole + ", " + "enabled");
// Return authenticated users + new ones during runtime
return new InMemoryUserDetailsManager(users);
@Autowired
public void configureGlobalSecurity(AuthenticationManagerBuilder auth) throws Exception
// Authenticate administrators in memory, with user details service
auth.userDetailsService(inMemoryUserDetailsManager());
Then, you can protect specific pages of your webapp by adding the path to the appropriate antMatchers() method:
protected void configure(HttpSecurity http) throws Exception
// Make login page and oauth token accessible without authentication
// Protect all pages and allow only admins and moderators to access them
http.csrf().disable()
.authorizeRequests()
.antMatchers("/home/login-page").permitAll()
.antMatchers("/oauth/token").permitAll()
.antMatchers("/home/**", "/admin/**"")
.access("hasAnyRole('ADMIN', 'MODERATOR')")
.and()
.formLogin()
.loginPage("/home/login-page")
.defaultSuccessUrl("/home/main", true)
.failureUrl("/home/login-page?fail=Invalid+login+details")
.and()
.logout().logoutSuccessUrl("/home/login-page")
.and()
.httpBasic().disable();
1
Thank you, I have just implemented it and it works!
– IoannisGk
Mar 1 at 21:50
add a comment |
First, you do not need to add an “authentication-manager” to your web.xml file. You have to create a SecurityConfiguration class that extends WebSecurityConfigurerAdapter. From there you can create the InMemoryUserDetailsManager bean as you see here:
// Bean that holds all authenticated users + new ones during runtime
@Bean
public InMemoryUserDetailsManager inMemoryUserDetailsManager()
final Properties users = new Properties();
// Get all administrators from the service
List<Administrator> theAdministrators = administratorService.getAdministrators();
// Iterate list and save current username, password and role
for (int i = 0; i < theAdministrators.size(); i++)
// Get current attributes from administrator object
String currentUsername = theAdministrators.get(i).getUsername();
String encryptedPassword = theAdministrators.get(i).getPassword();
String currentRole = theAdministrators.get(i).getRole();
// Decrypt current password
String currentPassword = strongTextEncryptorHelper.decryptPassword(encryptedPassword);
// Authenticate all administrators in memory and grant them their roles
users.put(currentUsername, currentPassword + ", " + "ROLE_" + currentRole + ", " + "enabled");
// Return authenticated users + new ones during runtime
return new InMemoryUserDetailsManager(users);
@Autowired
public void configureGlobalSecurity(AuthenticationManagerBuilder auth) throws Exception
// Authenticate administrators in memory, with user details service
auth.userDetailsService(inMemoryUserDetailsManager());
Then, you can protect specific pages of your webapp by adding the path to the appropriate antMatchers() method:
protected void configure(HttpSecurity http) throws Exception
// Make login page and oauth token accessible without authentication
// Protect all pages and allow only admins and moderators to access them
http.csrf().disable()
.authorizeRequests()
.antMatchers("/home/login-page").permitAll()
.antMatchers("/oauth/token").permitAll()
.antMatchers("/home/**", "/admin/**"")
.access("hasAnyRole('ADMIN', 'MODERATOR')")
.and()
.formLogin()
.loginPage("/home/login-page")
.defaultSuccessUrl("/home/main", true)
.failureUrl("/home/login-page?fail=Invalid+login+details")
.and()
.logout().logoutSuccessUrl("/home/login-page")
.and()
.httpBasic().disable();
1
Thank you, I have just implemented it and it works!
– IoannisGk
Mar 1 at 21:50
add a comment |
First, you do not need to add an “authentication-manager” to your web.xml file. You have to create a SecurityConfiguration class that extends WebSecurityConfigurerAdapter. From there you can create the InMemoryUserDetailsManager bean as you see here:
// Bean that holds all authenticated users + new ones during runtime
@Bean
public InMemoryUserDetailsManager inMemoryUserDetailsManager()
final Properties users = new Properties();
// Get all administrators from the service
List<Administrator> theAdministrators = administratorService.getAdministrators();
// Iterate list and save current username, password and role
for (int i = 0; i < theAdministrators.size(); i++)
// Get current attributes from administrator object
String currentUsername = theAdministrators.get(i).getUsername();
String encryptedPassword = theAdministrators.get(i).getPassword();
String currentRole = theAdministrators.get(i).getRole();
// Decrypt current password
String currentPassword = strongTextEncryptorHelper.decryptPassword(encryptedPassword);
// Authenticate all administrators in memory and grant them their roles
users.put(currentUsername, currentPassword + ", " + "ROLE_" + currentRole + ", " + "enabled");
// Return authenticated users + new ones during runtime
return new InMemoryUserDetailsManager(users);
@Autowired
public void configureGlobalSecurity(AuthenticationManagerBuilder auth) throws Exception
// Authenticate administrators in memory, with user details service
auth.userDetailsService(inMemoryUserDetailsManager());
Then, you can protect specific pages of your webapp by adding the path to the appropriate antMatchers() method:
protected void configure(HttpSecurity http) throws Exception
// Make login page and oauth token accessible without authentication
// Protect all pages and allow only admins and moderators to access them
http.csrf().disable()
.authorizeRequests()
.antMatchers("/home/login-page").permitAll()
.antMatchers("/oauth/token").permitAll()
.antMatchers("/home/**", "/admin/**"")
.access("hasAnyRole('ADMIN', 'MODERATOR')")
.and()
.formLogin()
.loginPage("/home/login-page")
.defaultSuccessUrl("/home/main", true)
.failureUrl("/home/login-page?fail=Invalid+login+details")
.and()
.logout().logoutSuccessUrl("/home/login-page")
.and()
.httpBasic().disable();
First, you do not need to add an “authentication-manager” to your web.xml file. You have to create a SecurityConfiguration class that extends WebSecurityConfigurerAdapter. From there you can create the InMemoryUserDetailsManager bean as you see here:
// Bean that holds all authenticated users + new ones during runtime
@Bean
public InMemoryUserDetailsManager inMemoryUserDetailsManager()
final Properties users = new Properties();
// Get all administrators from the service
List<Administrator> theAdministrators = administratorService.getAdministrators();
// Iterate list and save current username, password and role
for (int i = 0; i < theAdministrators.size(); i++)
// Get current attributes from administrator object
String currentUsername = theAdministrators.get(i).getUsername();
String encryptedPassword = theAdministrators.get(i).getPassword();
String currentRole = theAdministrators.get(i).getRole();
// Decrypt current password
String currentPassword = strongTextEncryptorHelper.decryptPassword(encryptedPassword);
// Authenticate all administrators in memory and grant them their roles
users.put(currentUsername, currentPassword + ", " + "ROLE_" + currentRole + ", " + "enabled");
// Return authenticated users + new ones during runtime
return new InMemoryUserDetailsManager(users);
@Autowired
public void configureGlobalSecurity(AuthenticationManagerBuilder auth) throws Exception
// Authenticate administrators in memory, with user details service
auth.userDetailsService(inMemoryUserDetailsManager());
Then, you can protect specific pages of your webapp by adding the path to the appropriate antMatchers() method:
protected void configure(HttpSecurity http) throws Exception
// Make login page and oauth token accessible without authentication
// Protect all pages and allow only admins and moderators to access them
http.csrf().disable()
.authorizeRequests()
.antMatchers("/home/login-page").permitAll()
.antMatchers("/oauth/token").permitAll()
.antMatchers("/home/**", "/admin/**"")
.access("hasAnyRole('ADMIN', 'MODERATOR')")
.and()
.formLogin()
.loginPage("/home/login-page")
.defaultSuccessUrl("/home/main", true)
.failureUrl("/home/login-page?fail=Invalid+login+details")
.and()
.logout().logoutSuccessUrl("/home/login-page")
.and()
.httpBasic().disable();
edited Mar 9 at 0:27
halfer
14.8k759118
14.8k759118
answered Feb 28 at 6:38
dpapdpap
1,3052925
1,3052925
1
Thank you, I have just implemented it and it works!
– IoannisGk
Mar 1 at 21:50
add a comment |
1
Thank you, I have just implemented it and it works!
– IoannisGk
Mar 1 at 21:50
1
1
Thank you, I have just implemented it and it works!
– IoannisGk
Mar 1 at 21:50
Thank you, I have just implemented it and it works!
– IoannisGk
Mar 1 at 21:50
add a comment |
There is one alternative, just make sure that the querys to retrieve the users and roles information are changed according to your db schema.
jdbc-authetnication
<authentication-manager>
<authentication-provider>
<jdbc-user-service data-source-ref="dataSource"
users-by-username-query=
"select username,password, enabled from users where username=?"
authorities-by-username-query=
"select username, role from user_roles where username =? " />
</authentication-provider>
</authentication-manager>
and the datasource is a bean
<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://localhost:3306/mydb" />
<property name="username" value="root" />
<property name="password" value="password" />
</bean>
here is a good example: http://www.mkyong.com/spring-security/spring-security-form-login-using-database/
add a comment |
There is one alternative, just make sure that the querys to retrieve the users and roles information are changed according to your db schema.
jdbc-authetnication
<authentication-manager>
<authentication-provider>
<jdbc-user-service data-source-ref="dataSource"
users-by-username-query=
"select username,password, enabled from users where username=?"
authorities-by-username-query=
"select username, role from user_roles where username =? " />
</authentication-provider>
</authentication-manager>
and the datasource is a bean
<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://localhost:3306/mydb" />
<property name="username" value="root" />
<property name="password" value="password" />
</bean>
here is a good example: http://www.mkyong.com/spring-security/spring-security-form-login-using-database/
add a comment |
There is one alternative, just make sure that the querys to retrieve the users and roles information are changed according to your db schema.
jdbc-authetnication
<authentication-manager>
<authentication-provider>
<jdbc-user-service data-source-ref="dataSource"
users-by-username-query=
"select username,password, enabled from users where username=?"
authorities-by-username-query=
"select username, role from user_roles where username =? " />
</authentication-provider>
</authentication-manager>
and the datasource is a bean
<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://localhost:3306/mydb" />
<property name="username" value="root" />
<property name="password" value="password" />
</bean>
here is a good example: http://www.mkyong.com/spring-security/spring-security-form-login-using-database/
There is one alternative, just make sure that the querys to retrieve the users and roles information are changed according to your db schema.
jdbc-authetnication
<authentication-manager>
<authentication-provider>
<jdbc-user-service data-source-ref="dataSource"
users-by-username-query=
"select username,password, enabled from users where username=?"
authorities-by-username-query=
"select username, role from user_roles where username =? " />
</authentication-provider>
</authentication-manager>
and the datasource is a bean
<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://localhost:3306/mydb" />
<property name="username" value="root" />
<property name="password" value="password" />
</bean>
here is a good example: http://www.mkyong.com/spring-security/spring-security-form-login-using-database/
answered Aug 23 '17 at 3:19
Daniel C.Daniel C.
2,87721019
2,87721019
add a comment |
add a comment |
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f45827327%2fhow-to-configure-spring-security-with-hibernate-and-xml%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
The UserDetailsService interface is used to retrieve user-related data. It has one method named loadUserByUsername() which finds a user entity based on the username and can be overridden to customize the process of finding the user. Please check link baeldung.com/spring-security-authentication-with-a-database
– Amit K Bist
Aug 23 '17 at 2:52