Spring Security UserDetailsService throws UsernameNotFoundException - java

In the Spring Security, they automatically match input username and password with the DB saved username and password. It returns bad credential when password is not matched. However, in my code, as long as I know, if the username also does not match with DB saved username they should return bad credential. However, in my code, bad credential are shown only when username is correct and password is wrong and when username is not in DB it throws usernmaenotfoundexception.
I know I wrote usernamenotfoundexception in loaduserByusername. However, should it be first to check from DB whether username is matched and if it is wrong then bad credentials should be returned? I found userdetailservice from internet and most of people wrote the code this way. Then how should we know id not matched.,,?
Thank you so much
UserDeatilSerivce.java
package com.group6.shopping.security;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import com.group6.shopping.members.dao.MembersDAO;
import org.springframework.ui.Model;
public class CustomMemDetailsService implements UserDetailsService{
#Autowired
MembersDAO membersDAO;
#Override
public UserDetails loadUserByUsername(String memId) {
System.out.println("loaduserByusername");
CustomMemDetails members = null;
try {
members = membersDAO.getMemById(memId);
if(members == null) {
throw new UsernameNotFoundException("username " + memId + " not found");
}
System.out.println("**************Found user***************");
System.out.println("id : " + members.getUsername());
return members;
} catch (Exception e) {
e.printStackTrace();
}
return members;
}
}
security-context.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:security="http://www.springframework.org/schema/security"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd">
<security:http pattern="/resources/**" security="none"/>
<security:http>
<security:intercept-url pattern="/everyone/**" access="permitAll"/>
<security:intercept-url pattern="/member/**" access="hasRole('ROLE_MEMBER')"/>
<security:intercept-url pattern="/admin/**" access="hasRole('ROLE_ADMIN')"/>
<security:form-login login-page="/everyone/login"
login-processing-url="/everyone/login/loginProcess"
default-target-url="/"
authentication-failure-handler-ref="loginFailureHandler"/>
<!-- 최대 한 개의 세션만 생성되도록 -->
<security:session-management invalid-session-url="/everyone/login">
<security:concurrency-control max-sessions="1"
expired-url="/everyone/login"
error-if-maximum-exceeded="true" />
</security:session-management>
</security:http>
<security:authentication-manager>
<security:authentication-provider user-service-ref="customMemService">
<security:password-encoder hash="bcrypt"/>
</security:authentication-provider>
</security:authentication-manager>
<bean id="bcryptPasswordEncoder" class="org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder" />
<bean id="loginFailureHandler" class="com.group6.shopping.security.LoginFailureHandler"/>
<context:component-scan base-package="com.group6.shopping.security" />
<bean id="customMemService" class="com.group6.shopping.security.CustomMemDetailsService" />
</beans>
LoginFailureHandler.java
package com.group6.shopping.security;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
public class LoginFailureHandler implements AuthenticationFailureHandler {
#Override
public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {
String msg = "";
if(exception instanceof UsernameNotFoundException){
System.out.println("username error");
msg = "Wrong id or password. Please re-enter";
}else if (exception instanceof BadCredentialsException){
System.out.println("bad credential");
msg = "Wrong id or password. Please re-enter";
}
request.setAttribute("msg", msg);
request.getRequestDispatcher("/everyone/login?error").forward(request, response);
}
}

I had miss understanding of spring security flow. It actually checks id and password after userdetailservice is ran. So, I just delete throws new UsernameNotFoundException and return new CustomMemDetails();
then in login failure handler.java just check exception is DisabledException

Related

#Autowired - No qualifying bean of type 'com.wusuq.dao.LoginDAO' available

The project structure is
Actually, I am integeration the Spring Security in my Spring MVC project. Simpley I want to do is to add the LoginDAO in the customAuthenticationProvider class. But I am getting this exception.
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.wusuq.dao.LoginDAO' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {#org.springframework.beans.factory.annotation.Autowired(required=true)}
at org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoMatchingBeanFound(DefaultListableBeanFactory.java:1486)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1104)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1066)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:585)
... 93 more
The CustomAuthenticationProvider class code is
package com.wusuq.security;
import java.util.ArrayList;
import java.util.List;
import com.wusuq.dao.LoginDAO;
#Component
public class CustomAuthenticationProvider implements AuthenticationProvider {
#Autowired
private LoginDAO login;
#Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException
{
String userName = authentication.getName();
String password = authentication.getCredentials().toString();
if (authorizedUser(userName, password))
{
List<GrantedAuthority> grantedAuths = new ArrayList<>();
grantedAuths.add(new SimpleGrantedAuthority("ROLE_ADMINN"));
Authentication auth = new UsernamePasswordAuthenticationToken(userName, password, grantedAuths);
System.out.println(auth.getAuthorities());
return auth;
}
else
{
throw new AuthenticationCredentialsNotFoundException("Invalid Credentials!");
}
}
private boolean authorizedUser(String userName, String password)
{
System.out.println("username is :" + userName+" and password is "+password );
if("Chandan".equals(userName) && "Chandan".equals(password))
return true;
return false;
}
#Override
public boolean supports(Class<?> authentication)
{
return UsernamePasswordAuthenticationToken.class.isAssignableFrom(authentication);
}
public LoginDAO getLogin() {
return login;
}
public void setLogin(LoginDAO login) {
this.login = login;
}
}
LoginDAO class code is
#Transactional
public class LoginDAO {
#Autowired
private SessionFactory sessionFactory;
Session session = null;
Criteria criteria = null;
Transaction tx = null;
public LoginDAO() {
super();
}
}
secirity-config.xml file
<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/security"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:beans="http://www.springframework.org/schema/beans"
xmlns:sec="http://www.springframework.org/schema/security"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="
http://www.springframework.org/schema/security
http://www.springframework.org/schema/security/spring-security-4.0.xsd
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.0.xsd">
<sec:http auto-config="true" use-expressions="true">
<sec:form-login login-page="/"
login-processing-url="/authenticateUser"
authentication-failure-url="/login" username-parameter="username"
password-parameter="password"
default-target-url="/menu"
always-use-default-target="true"
/>
<sec:access-denied-handler error-page="/jsp/403.jsp" />
<sec:intercept-url pattern="/" access="permitAll" />
<sec:intercept-url pattern="/JS/**" access="permitAll" />
<sec:intercept-url pattern="/img/**" access="permitAll" />
<!-- <sec:intercept-url pattern="/JS/**" access="permitAll" /> -->
<sec:intercept-url pattern="/**" access="hasAuthority('ROLE_ADMINN')" />
<sec:session-management invalid-session-url="/login" />
<sec:logout delete-cookies="JSESSIONID" logout-url="/logout" />
</sec:http>
<context:component-scan base-package="com.wusuq.security" />
<sec:authentication-manager>
<authentication-provider ref="customAuthenticationProvider" />
</sec:authentication-manager>
</beans:beans>
Can some please guide me how to fix this issue I want to Autowire the LoginDAO in CustomAuthentionProvider class to authenticate the user from Databbase. Help will be appreciated. Thanks

How to add REST basic authentication to existing XML Spring Security config?

I'm working with Spring Security 4 XML based configuration.
This is my configuration (security.xml):
<!--?xml version="1.0" encoding="UTF-8"?-->
<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-3.0.xsd
http://www.springframework.org/schema/security
http://www.springframework.org/schema/security/spring-security.xsd">
<http create-session="always"
use-expressions="true"
authentication-manager-ref="authenticationManager"
entry-point-ref="authenticationEntryPoint">
<csrf disabled="true" />
<intercept-url pattern="/**" access="hasRole('USER')" />
<form-login authentication-success-handler-ref="customAuthenticationSuccessHandler" />
<logout />
</http>
<authentication-manager alias="authenticationManager">
<authentication-provider user-service-ref="userDao"></authentication-provider>
</authentication-manager>
</beans:beans>
Here is my CustomEntryPoint:
#Component
public class CustomEntryPoint implements AuthenticationEntryPoint {
#Override
public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {
System.out.println("Entering commence due to failed Authentication");
response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Unauthorized Access!");
}
}
and my UserDao (for future reading credentials from file):
public class UserDao implements UserDetailsService {
#Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
String password = readPasswordFromFileOrDatabase(username);
if (password == null) throw new UsernameNotFoundException("failure");
return User.withUsername("user").password(password).authorities("ROLE_USER").build();
}
private String readPasswordFromFileOrDatabase(String username) {
if (username.equals("user")) return "q";
return null;
}
}
And it looks like REST feauture doesn't work, when I send POST through Postman to http://localhost:8080/login with user/password: user/q it says
Bad credentials
But when I do the same thing through form in browser it works fine.
So, is there any way to make REST features work?
The following code will give you base64 encoded value of username and password. Use that to add a HTTP header as following:
String plainClientCredentials="myusername:mypassword";
String base64ClientCredentials = new String(Base64.encodeBase64(plainClientCredentials.getBytes()));
System.out.println(base64ClientCredentials);`
In headers set this:
Key- Authorization, Value-Basicbase64ClientCredentials
Suppose the code prints 123&78#
then value would be Basic123&78#.

spring login script how to check the db is connected?

i'm learning spring framework, and i created a login app according to
http://o7planning.org/web/fe/default/en/document/29799/simple-login-web-application-using-spring-mvc-spring-security-and-spring-jdbc
but when i try to login using the username & password at database, it redirects me to error, here is the xml
spring-security.xml:
<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/security"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:beans="http://www.springframework.org/schema/beans"
xsi:schemaLocation="http://www.springframework.org/schema/security
http://www.springframework.org/schema/security/spring-security-3.2.xsd
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.1.xsd">
<http use-expressions="true">
<intercept-url pattern="/" access="isAnonymous()" />
<intercept-url pattern="/welcome" access="isAnonymous()" />
<intercept-url pattern="/login" access="isAnonymous()" />
<intercept-url pattern="/logout" access="isAnonymous()" />
<intercept-url pattern="/userInfo"
access="hasAnyRole('ROLE_USER', 'ROLE_ADMIN')" />
<intercept-url pattern="/admin" access="hasRole('ROLE_ADMIN')" />
<intercept-url pattern="/other/**" access="isAuthenticated()" />
<access-denied-handler error-page="/403" />
<form-login login-page='/login' login-processing-url="/j_spring_security_check"
default-target-url="/userInfo" always-use-default-target="false"
authentication-failure-url="/login?error=true" username-parameter="username"
password-parameter="password" />
<logout logout-url="/logout" logout-success-url="/logoutSuccessful"
delete-cookies="JSESSIONID" invalidate-session="true" />
</http>
<authentication-manager>
<!-- authentication from database -->
<authentication-provider>
<jdbc-user-service data-source-ref="myDataSource"
users-by-username-query="select username,password, enabled from users where username=?"
authorities-by-username-query="select username, role from users where username=?" />
</authentication-provider>
</authentication-manager>
</beans:beans>
data-source-cfg.xml:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="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-4.1.xsd">
<bean id="myDataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://localhost:3306/testdb_o7" />
<property name="username" value="root" />
<property name="password" value="" />
</bean>
</beans>
i use mysql, how can i check the app is connected to DB and retrieved the right username & password sucessfully
<beans:bean id="customUserDetailsService" class="com.myclass.dao.SimpleUserDetailsService">
</beans:bean>
<authentication-manager>
<authentication-provider user-service-ref="customUserDetailsService">
<password-encoder hash="md5"> </password-encoder>
<!-- [plaintext, sha, sha-256, md5, md4, {sha}, {ssha}] -->
</authentication-provider>
</authentication-manager>
<beans:bean id="authenticationFailureHandler" class="org.springframework.security.web.authentication.ExceptionMappingAuthenticationFailureHandler">
<beans:property name="exceptionMappings">
<beans:props>
<beans:prop key="org.springframework.security.core.userdetails.UsernameNotFoundException">/login.action?error=1</beans:prop>
</beans:props>
</beans:property>
</beans:bean>
In SimpleUserDetailService for example you will test and check user from DB
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Repository;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import UserBean;
#Repository
#Service
#Transactional(readOnly=true)
public class SimpleUserDetailsService implements UserDetailsService {
#Autowired
private UserDao userDAO;
private UserBean domainUser;
public UserDetails loadUserByUsername(String login)
throws UsernameNotFoundException {
domainUser = userDAO.getUser(login);
boolean enabled = true;
boolean disabled = false;
boolean accountNonExpired = true;
boolean accountExpired = false;
boolean credentialsNonExpired = true;
boolean credentialsExpired = false;
boolean accountNonLocked = true;
boolean accountLocked = false;
if (null != domainUser){
return new User(
domainUser.getUsername(), //getLogin(),
domainUser.getPassword(),
enabled,
accountNonExpired,
credentialsNonExpired,
accountNonLocked,
getAuthorities(domainUser.getIduser() ) );
} else {
return new User(
"**20**",
"**//**",
disabled,
accountExpired,
credentialsExpired,
accountLocked,
getAuthorities(-20 ) ) ;
}
}
public Collection<? extends GrantedAuthority> getAuthorities(Integer userid) {
List<GrantedAuthority> authList = getGrantedAuthorities(getRoles(userid));
return authList;
}
public List<String> getRoles(Integer userid) {
List<String> roles = new ArrayList<String>();
roles = userDAO.getUserRoles(userid);
return roles;
}
public static List<GrantedAuthority> getGrantedAuthorities(List<String> roles) {
List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
for (String role : roles) {
authorities.add(new SimpleGrantedAuthority(role));
}
return authorities;
}
}
in userDAO.getUser(login) you select user from table_user where user_name=:login or email = :login

spring-security form authentication migration to annotations

I have the following spring-security config:
<?xml version="1.0" encoding="UTF-8"?>
<b:beans xmlns="http://www.springframework.org/schema/security"
xmlns:b="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 use-expressions="true">
<intercept-url pattern="/edit/**" access="hasRole('EDITOR')" />
<form-login login-page="/login" authentication-failure-url="/loginfailed" />
<logout logout-success-url="/" delete-cookies="JSESSIONID" />
<remember-me user-service-ref="userDetailsService"/>
</http>
<b:bean id="encoder"
class="org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder" />
<authentication-manager>
<authentication-provider user-service-ref="userDetailsService">
<password-encoder ref="encoder" />
</authentication-provider>
</authentication-manager>
</b:beans>
And I'm trying to migrate it to annotation-based config:
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
#Configuration
#EnableWebSecurity
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
#Autowired
private UserDetailsService userDetailsService;
#Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests().antMatchers("/edit/**").hasRole("EDITOR").and()
.logout().logoutSuccessUrl("/").deleteCookies("JSESSIONID").and()
.formLogin().loginPage("/login").failureUrl("/loginfailed").and()
.rememberMe().userDetailsService(userDetailsService);
}
#Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userDetailsService).passwordEncoder(encoder());
}
#Bean
public PasswordEncoder encoder() {
return new BCryptPasswordEncoder();
}
}
Also I have social-networks sign-in functionality and for that I used autowired RequestCache. And this bean does not appear in the application context with annotation based configuration. What I am missing?
RequestCache problem is solved the following way:
#Bean
public RequestCache requestCache() {
return new HttpSessionRequestCache();
}
And with changing configuration:
http
.requestCache().requestCache(requestCache()).and()
.authorizeRequests().antMatchers("/edit/**").hasRole("EDITOR").and()...
Also migrating to annotation-based config many defaults are changing - "j_username" to "username", "j_password" to "password", "j_spring_security_check" to "login", "j_spring_security_logout" to "logout" and csrf hidden token in forms becomes required.

Spring security user role and access jsp

I am new to spring security. I have two user roles like Admin and Common Users. I want to access some jsp only access by the admin users, but the problem is once a user is log out he/she still can access the jsp page which i put restricted in spring security config.
Let me know what i am doing here is the correct or not?
Thank you
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">
<intercept-url pattern="/admin/**" access="ROLE_ADMIN" />
<intercept-url pattern="/user/**" access="ROLE_USER" />
<form-login login-page="/login" default-target-url="/welcome"
authentication-failure-url="/loginfailed" />
<logout logout-success-url="/logout" />
</http>
<beans:bean id="customUserDetailsService"
class="com.nikunj.javabrains.services.CustomUserDetailsService"></beans:bean>
<authentication-manager>
<authentication-provider user-service-ref="customUserDetailsService">
</authentication-provider>
</authentication-manager>
//------------------------------
Controller
package com.nikunj.javabrains.controller;
import java.security.Principal;
import javax.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.annotation.Secured;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import com.nikunj.javabrains.domain.User;
import com.nikunj.javabrains.services.UserService;
#Controller
public class UserController {
#Autowired
private UserService userService;
#RequestMapping(value = "/welcome", method = RequestMethod.GET)
public String printWelcome(ModelMap model, Principal principal,
HttpServletRequest request) {
String name = principal.getName(); // get logged in username
model.addAttribute("username", name);
model.addAttribute("message",
"Spring Security login + database example");
if (request.isUserInRole("ROLE_ADMIN")) {
return "admin_page";
}
return "common_page";
}
#RequestMapping(value = "/login", method = RequestMethod.GET)
public String login(ModelMap model) {
return "login";
}
#RequestMapping(value = "/loginfailed", method = RequestMethod.GET)
public String loginerror(ModelMap model) {
model.addAttribute("error", "true");
return "login";
}
#RequestMapping(value = "/logout", method = RequestMethod.GET)
public String logout(ModelMap model) {
return "login";
}
#RequestMapping("/regiPage")
public String regiPage(#ModelAttribute("user") User user,
BindingResult result) {
return "registration";
}
#RequestMapping(value = "/saveUser", method = RequestMethod.POST)
public String saveUserData(#ModelAttribute("user") User user,
BindingResult result) {
userService.addUser(user);
return "login";
}
}
</beans:beans>
//------------------------
CustomServiceClass
import com.nikunj.javabrains.dao.UserDao;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
#Service
#Transactional(readOnly=true)
public class CustomUserDetailsService implements UserDetailsService {
#Autowired
private UserDao userDAO;
public UserDetails loadUserByUsername(String username)
throws UsernameNotFoundException {
com.nikunj.javabrains.domain.User domainUser = userDAO.getUser(username);
boolean enabled = true;
boolean accountNonExpired = true;
boolean credentialsNonExpired = true;
boolean accountNonLocked = true;
System.out.println("*************************************");
System.out.println(domainUser.getId());
return new User(
domainUser.getUsername(),
domainUser.getPassword(),
enabled,
accountNonExpired,
credentialsNonExpired,
accountNonLocked,
getAuthorities(domainUser.getId())
);
}
public Collection<? extends GrantedAuthority> getAuthorities(Integer role) {
List<GrantedAuthority> authList = getGrantedAuthorities(getRoles(role));
return authList;
}
public List<String> getRoles(Integer role) {
List<String> roles = new ArrayList<String>();
if (role.intValue() == 1) {
roles.add("ROLE_ADMIN");
} else {
roles.add("ROLE_USER");
}
return roles;
}
public static List<GrantedAuthority> getGrantedAuthorities(List<String> roles) {
List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
for (String role : roles) {
authorities.add(new SimpleGrantedAuthority(role));
}
return authorities;
}
}
//---------------------------
#Controller
public class AdminController {
#Autowired
private UserService userService;
#RequestMapping(value = "/admininput", method = RequestMethod.GET)
public String login(ModelMap model) {
System.out.println("*************************");
return "admininputpage";
}
}
Ok, so as per your last comment, the URL /admininput is being accessed by everyone.
This is the behaviour I would expect, as there is no security rules defined for this URL pattern.
In your security config you define the following rules:
<intercept-url pattern="/admin/**" access="ROLE_ADMIN" />
<intercept-url pattern="/user/**" access="ROLE_USER" />
This config will require all resources with the URL pattern /admin/** to be logged in with role ROLE_ADMIN and all resources with URL pattern /user/** to be logged in with role ROLE_USER. All other URL patterns will be permitAll.
If you want to restrict that URL you will either need to change the URL pattern, or add an intercept rule. E.g.
Change URL from /admininput to /admin/input or /admin/admininput etc
Alternatively, add an explicit intercept rule (or another pattern based rule) to cover this URL:
<intercept-url pattern="/admininput" access="ROLE_ADMIN" />
(although, not a good idea to have explicit interceptor rules for every URL! so would be better to change URL if possible to the convention you already defined)
you can use unique session id in url .if destroy session after logout or by copying url,URL can't be accessible without login URL with logged session.

Categories

Resources