我使用spring security 4.1.1和spring boot进行身份验证,它的工作非常好。现在我开始实现,记住下面是我的配置代码
@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
CustomAuthenticationProvider customAuthenticationProvider;
// UserDetailsService userDetailsService;
@Autowired
UserDetailsService userDetailsService;
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests().antMatchers("/", "/login", "/signup","/logout", "/loginProcess","/public/**","/forgotpassword","/forgot-password*","/isUserExists","/emailForgot","/verify-user*").permitAll()
.anyRequest().authenticated()
.and()
.csrf().disable()
.rememberMe().key("tokenkey").rememberMeParameter("_spring_security_remember_me").rememberMeCookieName("myremembermecookie").tokenValiditySeconds(1209600).alwaysRemember(true).userDetailsService(userDetailsService)
.and()
.formLogin().loginPage("/login").loginProcessingUrl("/loginProcess").defaultSuccessUrl("/home")
.failureUrl("/login?error").usernameParameter("userName").passwordParameter("userPassword").permitAll()
.and().logout().logoutUrl("/logout").logoutSuccessUrl("/login?logout").deleteCookies("JSESSIONID")
.invalidateHttpSession(true).permitAll().and().headers().defaultsDisabled().cacheControl();
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.authenticationProvider(customAuthenticationProvider);
auth.userDetailsService(userDetailsService);
}
}
这是我的自定义身份验证提供程序代码
@Component
public class CustomAuthenticationProvider implements AuthenticationProvider{
public static final Logger logger = LoggerFactory.getLogger(CustomAuthenticationProvider.class);
@Autowired
WyzbeeGatewayService sdkService;
@Autowired
UserData userData;
@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
logger.info("###############################################################################################");
logger.info(authentication.getName()+" "+authentication.getCredentials());
logger.info("###############################################################################################");
try {
final String userToken = sdkService.login(authentication.getName(), authentication.getCredentials().toString());
final LoginResponse responseValidate = sdkService.validateUser(authentication.getName(), authentication.getCredentials().toString());
userData.setUserTenantList(responseValidate.getUserTenantList());
List<GrantedAuthority> grantedAuths = new ArrayList<GrantedAuthority>();
userData.setUserName(authentication.getName());
userData.setPasswrod(authentication.getCredentials().toString());
userData.setGrantedAuths(grantedAuths);
userData.setUserToken(userToken);
UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken = new UsernamePasswordAuthenticationToken(authentication.getName(), authentication.getCredentials().toString(), grantedAuths);
logger.info("checking for authentication "+usernamePasswordAuthenticationToken.isAuthenticated());
//UserDetails user = new User(authentication.getName(), authentication.getCredentials().toString(), true, true, true, true, grantedAuths);
//SecurityContextHolder.getContext().setAuthentication(new RememberMeAuthenticationToken("tokenkey", authentication.getName(), grantedAuths));
/* UserService userService = new UserService();
userService.setUserDetails(user);*/
return usernamePasswordAuthenticationToken;
} catch (final WyzbeeException e) {
throw new UsernameNotFoundException("Username " + authentication.getName() + " not found");
}
}
@Override
public boolean supports(Class<?> arg0) {
return true;
}
由于我无法直接访问数据库,因此我们有一个用于登录和注销的休息呼叫,因此我无法直接使用UserDetailsService
我使用AuthenticationProvider
检查凭据但是,春天文档说如果你想使用内置的记住我机制我们应该UserDetailsService
所以我这样实现了
@Service
public class UserService implements UserDetailsService {
UserDetails user= null;
public static final Logger logger = LoggerFactory.getLogger(UserService.class);
@Autowired
WyzbeeGatewayService sdkService;
@Autowired
UserData userData;
@Override
public UserDetails loadUserByUsername(String userName) throws UsernameNotFoundException {
/*logger.info("###############################################################################################");
logger.info("User Service "+userData.getUserName());
logger.info("###############################################################################################");*/
return new User(userData.getUserName(), userData.getPasswrod(), true, true, true, true, userData.getGrantedAuths());
}
public void setUserDetails(UserDetails user){
this.user = user;
}
}
问题是当我在登录后第一次登录时生成并存储在浏览器中我关闭浏览器而没有注销当我再次访问我的URL时它再次移动到登录页面。我保留了index.jsp中的任何内容,只是维护它以重定向到登录页面。
调试内容
2016-09-27 11:51:24 DEBUG AntPathRequestMatcher:157 - Checking match of request : '/public/css/style.css'; against '/'
2016-09-27 11:51:24 DEBUG AntPathRequestMatcher:157 - Checking match of request : '/public/css/style.css'; against '/login'
2016-09-27 11:51:24 DEBUG AntPathRequestMatcher:157 - Checking match of request : '/public/css/style.css'; against '/signup'
2016-09-27 11:51:24 DEBUG DispatcherServlet:1044 - Null ModelAndView returned to DispatcherServlet with name 'dispatcherServlet': assuming HandlerAdapter completed request handling
2016-09-27 11:51:24 DEBUG AntPathRequestMatcher:157 - Checking match of request : '/public/css/style.css'; against '/logout'
2016-09-27 11:51:24 DEBUG DispatcherServlet:1000 - Successfully completed request
2016-09-27 11:51:24 DEBUG AntPathRequestMatcher:157 - Checking match of request : '/public/css/style.css'; against '/loginProcess'
2016-09-27 11:51:24 DEBUG ExceptionTranslationFilter:117 - Chain processed normally
2016-09-27 11:51:24 DEBUG AntPathRequestMatcher:157 - Checking match of request : '/public/css/style.css'; against '/public/**'
2016-09-27 11:51:24 DEBUG SecurityContextPersistenceFilter:119 - SecurityContextHolder now cleared, as request processing completed
2016-09-27 11:51:24 DEBUG FilterSecurityInterceptor:219 - Secure object: FilterInvocation: URL: /public/css/style.css; Attributes: [permitAll]
2016-09-27 11:51:24 DEBUG OrderedRequestContextFilter:104 - Cleared thread-bound request context: org.apache.catalina.connector.RequestFacade@4954e173
2016-09-27 11:51:24 DEBUG FilterSecurityInterceptor:348 - Previously Authenticated: org.springframework.security.authentication.UsernamePasswordAuthenticationToken@7a88a3ec: Principal: swapnil1472; Credentials: [PROTECTED]; Authenticated: true; Details: org.springframework.security.web.authentication.WebAuthenticationDetails@380f4: RemoteIpAddress: 0:0:0:0:0:0:0:1; SessionId: 3B315D5D7EF75385D93713710B62079C; Not granted any authorities
2016-09-27 11:51:24 DEBUG AffirmativeBased:66 - Voter: org.springframework.security.web.access.expression.WebExpressionVoter@5de2ed51, returned: 1
2016-09-27 11:51:24 DEBUG FilterSecurityInterceptor:243 - Authorization successful
2016-09-27 11:51:24 DEBUG FilterSecurityInterceptor:256 - RunAsManager did not change Authentication object
2016-09-27 11:51:24 DEBUG FilterChainProxy:310 - /public/css/style.css reached end of additional filter chain; proceeding with original chain
2016-09-27 11:51:24 DEBUG DispatcherServlet:865 - DispatcherServlet with name 'dispatcherServlet' processing GET request for [/virtual/public/css/style.css]
2016-09-27 11:51:24 DEBUG SimpleUrlHandlerMapping:190 - Matching patterns for request [/public/css/style.css] are [/public/**, /**]
2016-09-27 11:51:24 DEBUG SimpleUrlHandlerMapping:219 - URI Template variables for request [/public/css/style.css] are {}
2016-09-27 11:51:24 DEBUG SimpleUrlHandlerMapping:140 - Mapping [/public/css/style.css] to HandlerExecutionChain with handler [ResourceHttpRequestHandler [locations=[class path resource [static/public/]], resolvers=[org.springframework.web.servlet.resource.PathResourceResolver@1c026d4e]]] and 1 interceptor
2016-09-27 11:51:24 DEBUG DispatcherServlet:951 - Last-Modified value for [/virtual/public/css/style.css] is: -1
2016-09-27 11:51:24 DEBUG DispatcherServlet:1044 - Null ModelAndView returned to DispatcherServlet with name 'dispatcherServlet': assuming HandlerAdapter completed request handling
2016-09-27 11:51:24 DEBUG DispatcherServlet:1000 - Successfully completed request
2016-09-27 11:51:24 DEBUG ExceptionTranslationFilter:117 - Chain processed normally
2016-09-27 11:51:24 DEBUG SecurityContextPersistenceFilter:119 - SecurityContextHolder now cleared, as request processing completed
2016-09-27 11:51:24 DEBUG OrderedRequestContextFilter:104 - Cleared thread-bound request context: org.apache.catalina.connector.RequestFacade@634ebe6
2016-09-27 11:51:24 DEBUG OrderedRequestContextFilter:114 - Bound request context to thread: org.apache.catalina.connector.RequestFacade@634ebe6
2016-09-27 11:51:24 DEBUG OrderedRequestContextFilter:114 - Bound request context to thread: org.apache.catalina.connector.RequestFacade@4954e173
2016-09-27 11:51:24 DEBUG FilterChainProxy:325 - /public/css/fonts/eau_sans_book-webfont.woff at position 1 of 12 in additional filter chain; firing Filter: 'WebAsyncManagerIntegrationFilter'
2016-09-27 11:51:24 DEBUG FilterChainProxy:325 - /public/css/fonts/eau_sans_bold-webfont.woff at position 1 of 12 in additional filter chain; firing Filter: 'WebAsyncManagerIntegrationFilter'
2016-09-27 11:51:24 DEBUG FilterChainProxy:325 - /public/css/fonts/eau_sans_book-webfont.woff at position 2 of 12 in additional filter chain; firing Filter: 'SecurityContextPersistenceFilter'
2016-09-27 11:51:24 DEBUG FilterChainProxy:325 - /public/css/fonts/eau_sans_bold-webfont.woff at position 2 of 12 in additional filter chain; firing Filter: 'SecurityContextPersistenceFilter'
2016-09-27 11:51:24 DEBUG HttpSessionSecurityContextRepository:207 - Obtained a valid SecurityContext from SPRING_SECURITY_CONTEXT: 'org.springframework.security.core.context.SecurityContextImpl@7a88a3ec: Authentication: org.springframework.security.authentication.UsernamePasswordAuthenticationToken@7a88a3ec: Principal: swapnil1472; Credentials: [PROTECTED]; Authenticated: true; Details: org.springframework.security.web.authentication.WebAuthenticationDetails@380f4: RemoteIpAddress: 0:0:0:0:0:0:0:1; SessionId: 3B315D5D7EF75385D93713710B62079C; Not granted any authorities'
2016-09-27 11:51:24 DEBUG HttpSessionSecurityContextRepository:207 - Obtained a valid SecurityContext from SPRING_SECURITY_CONTEXT: 'org.springframework.security.core.context.SecurityContextImpl@7a88a3ec: Authentication: org.springframework.security.authentication.UsernamePasswordAuthenticationToken@7a88a3ec: Principal: swapnil1472; Credentials: [PROTECTED]; Authenticated: true; Details: org.springframework.security.web.authentication.WebAuthenticationDetails@380f4: RemoteIpAddress: 0:0:0:0:0:0:0:1; SessionId: 3B315D5D7EF75385D93713710B62079C; Not granted any authorities'
2016-09-27 11:51:24 DEBUG FilterChainProxy:325 - /public/css/fonts/eau_sans_book-webfont.woff at position 3 of 12 in additional filter chain; firing Filter: 'HeaderWriterFilter'
2016-09-27 11:51:24 DEBUG FilterChainProxy:325 - /public/css/fonts/eau_sans_bold-webfont.woff at position 3 of 12 in additional filter chain; firing Filter: 'HeaderWriterFilter'
2016-09-27 11:51:24 DEBUG FilterChainProxy:325 - /public/css/fonts/eau_sans_book-webfont.woff at position 4 of 12 in additional filter chain; firing Filter: 'LogoutFilter'
2016-09-27 11:51:24 DEBUG FilterChainProxy:325 - /public/css/fonts/eau_sans_bold-webfont.woff at position 4 of 12 in additional filter chain; firing Filter: 'LogoutFilter'
2016-09-27 11:51:24 DEBUG OrRequestMatcher:65 - Trying to match using Ant [pattern='/logout', GET]
2016-09-27 11:51:24 DEBUG OrRequestMatcher:65 - Trying to match using Ant [pattern='/logout', GET]
2016-09-27 11:51:24 DEBUG AntPathRequestMatcher:157 - Checking match of request : '/public/css/fonts/eau_sans_bold-webfont.woff'; against '/logout'
2016-09-27 11:51:24 DEBUG OrRequestMatcher:65 - Trying to match using Ant [pattern='/logout', POST]
2016-09-27 11:51:24 DEBUG AntPathRequestMatcher:137 - Request 'GET /public/css/fonts/eau_sans_bold-webfont.woff' doesn't match 'POST /logout
2016-09-27 11:51:24 DEBUG OrRequestMatcher:65 - Trying to match using Ant [pattern='/logout', PUT]
2016-09-27 11:51:24 DEBUG AntPathRequestMatcher:137 - Request 'GET /public/css/fonts/eau_sans_bold-webfont.woff' doesn't match 'PUT /logout
2016-09-27 11:51:24 DEBUG OrRequestMatcher:65 - Trying to match using Ant [pattern='/logout', DELETE]
2016-09-27 11:51:24 DEBUG AntPathRequestMatcher:137 - Request 'GET /public/css/fonts/eau_sans_bold-webfont.woff' doesn't match 'DELETE /logout
2016-09-27 11:51:24 DEBUG OrRequestMatcher:72 - No matches found
2016-09-27 11:51:24 DEBUG AntPathRequestMatcher:157 - Checking match of request : '/public/css/fonts/eau_sans_book-webfont.woff'; against '/logout'
2016-09-27 11:51:24 DEBUG FilterChainProxy:325 - /public/css/fonts/eau_sans_bold-webfont.woff at position 5 of 12 in additional filter chain; firing Filter: 'UsernamePasswordAuthenticationFilter'
2016-09-27 11:51:24 DEBUG AntPathRequestMatcher:137 - Request 'GET /public/css/fonts/eau_sans_bold-webfont.woff' doesn't match 'POST /loginProcess
2016-09-27 11:51:24 DEBUG OrRequestMatcher:65 - Trying to match using Ant [pattern='/logout', POST]
2016-09-27 11:51:24 DEBUG AntPathRequestMatcher:137 - Request 'GET /public/css/fonts/eau_sans_book-webfont.woff' doesn't match 'POST /logout
2016-09-27 11:51:24 DEBUG OrRequestMatcher:65 - Trying to match using Ant [pattern='/logout', PUT]
2016-09-27 11:51:24 DEBUG AntPathRequestMatcher:137 - Request 'GET /public/css/fonts/eau_sans_book-webfont.woff' doesn't match 'PUT /logout
2016-09-27 11:51:24 DEBUG OrRequestMatcher:65 - Trying to match using Ant [pattern='/logout', DELETE]
2016-09-27 11:51:24 DEBUG AntPathRequestMatcher:137 - Request 'GET /public/css/fonts/eau_sans_book-webfont.woff' doesn't match 'DELETE /logout
2016-09-27 11:51:24 DEBUG OrRequestMatcher:72 - No matches found
2016-09-27 11:51:24 DEBUG FilterChainProxy:325 - /public/css/fonts/eau_sans_bold-webfont.woff at position 6 of 12 in additional filter chain; firing Filter: 'RequestCacheAwareFilter'
2016-09-27 11:51:24 DEBUG FilterChainProxy:325 - /public/css/fonts/eau_sans_book-webfont.woff at position 5 of 12 in additional filter chain; firing Filter: 'UsernamePasswordAuthenticationFilter'
2016-09-27 11:51:24 DEBUG AntPathRequestMatcher:137 - Request 'GET /public/css/fonts/eau_sans_book-webfont.woff' doesn't match 'POST /loginProcess
2016-09-27 11:51:24 DEBUG FilterChainProxy:325 - /public/css/fonts/eau_sans_bold-webfont.woff at position 7 of 12 in additional filter chain; firing Filter: 'SecurityContextHolderAwareRequestFilter'
2016-09-27 11:51:24 DEBUG FilterChainProxy:325 - /public/css/fonts/eau_sans_book-webfont.woff at position 6 of 12 in additional filter chain; firing Filter: 'RequestCacheAwareFilter'
2016-09-27 11:51:24 DEBUG FilterChainProxy:325 - /public/css/fonts/eau_sans_book-webfont.woff at position 7 of 12 in additional filter chain; firing Filter: 'SecurityContextHolderAwareRequestFilter'
2016-09-27 11:51:24 DEBUG FilterChainProxy:325 - /public/css/fonts/eau_sans_bold-webfont.woff at position 8 of 12 in additional filter chain; firing Filter: 'RememberMeAuthenticationFilter'
2016-09-27 11:51:24 DEBUG FilterChainProxy:325 - /public/css/fonts/eau_sans_book-webfont.woff at position 8 of 12 in additional filter chain; firing Filter: 'RememberMeAuthenticationFilter'
2016-09-27 11:51:24 DEBUG RememberMeAuthenticationFilter:154 - SecurityContextHolder not populated with remember-me token, as it already contained: 'org.springframework.security.authentication.UsernamePasswordAuthenticationToken@7a88a3ec: Principal: swapnil1472; Credentials: [PROTECTED]; Authenticated: true; Details: org.springframework.security.web.authentication.WebAuthenticationDetails@380f4: RemoteIpAddress: 0:0:0:0:0:0:0:1; SessionId: 3B315D5D7EF75385D93713710B62079C; Not granted any authorities'
2016-09-27 11:51:24 DEBUG RememberMeAuthenticationFilter:154 - SecurityContextHolder not populated with remember-me token, as it already contained: 'org.springframework.security.authentication.UsernamePasswordAuthenticationToken@7a88a3ec: Principal: swapnil1472; Credentials: [PROTECTED]; Authenticated: true; Details: org.springframework.security.web.authentication.WebAuthenticationDetails@380f4: RemoteIpAddress: 0:0:0:0:0:0:0:1; SessionId: 3B315D5D7EF75385D93713710B62079C; Not granted any authorities'
2016-09-27 11:51:24 DEBUG FilterChainProxy:325 - /public/css/fonts/eau_sans_book-webfont.woff at position 9 of 12 in additional filter chain; firing Filter: 'AnonymousAuthenticationFilter'
2016-09-27 11:51:24 DEBUG FilterChainProxy:325 - /public/css/fonts/eau_sans_bold-webfont.woff at position 9 of 12 in additional filter chain; firing Filter: 'AnonymousAuthenticationFilter'
2016-09-27 11:51:24 DEBUG AnonymousAuthenticationFilter:106 - SecurityContextHolder not populated with anonymous token, as it already contained: 'org.springframework.security.authentication.UsernamePasswordAuthenticationToken@7a88a3ec: Principal: swapnil1472; Credentials: [PROTECTED]; Authenticated: true; Details: org.springframework.security.web.authentication.WebAuthenticationDetails@380f4: RemoteIpAddress: 0:0:0:0:0:0:0:1; SessionId: 3B315D5D7EF75385D93713710B62079C; Not granted any authorities'