本文将带您了解关于用于Web的RESTFul和FormLogin的新内容,同时我们还将为您解释Cookies的SpringSecurityHTTPBasic-批注的相关知识,另外,我们还将为您提供关于
本文将带您了解关于用于Web的RESTFul和FormLogin的新内容,同时我们还将为您解释Cookies的Spring Security HTTP Basic-批注的相关知识,另外,我们还将为您提供关于AngularJS $Http CORS与Spring Rest&Security中的后端、org.springframework.security.web.access.expression.DefaultWebSecurityExpressionHandler的实例源码、org.springframework.security.web.access.expression.WebSecurityExpressionRoot的实例源码、org.springframework.security.web.context.HttpRequestResponseHolder的实例源码的实用信息。
本文目录一览:- 用于Web的RESTFul和FormLogin(Cookies)的Spring Security HTTP Basic-批注(如何在web应用里面配置spring)
- AngularJS $Http CORS与Spring Rest&Security中的后端
- org.springframework.security.web.access.expression.DefaultWebSecurityExpressionHandler的实例源码
- org.springframework.security.web.access.expression.WebSecurityExpressionRoot的实例源码
- org.springframework.security.web.context.HttpRequestResponseHolder的实例源码
用于Web的RESTFul和FormLogin(Cookies)的Spring Security HTTP Basic-批注(如何在web应用里面配置spring)
具体而言
我只想对特定的网址格式进行HTTP基本身份验证。
详细
我正在为我的应用程序创建一个API接口,需要通过简单的HTTP基本身份验证进行身份验证。但其他网页应不使用HTTP基本而是在正常的形式登录。
当前配置-不起作用
@Overrideprotected void configure(HttpSecurity http) throws Exception { http //HTTP Security .csrf().disable() //Disable CSRF .authorizeRequests() //Authorize Request Configuration .antMatchers("/connect/**").permitAll() .antMatchers("/", "/register").permitAll() .antMatchers("/admin/**").hasRole("ADMIN") .antMatchers("/api/**").hasRole("API") .anyRequest().authenticated() .and() //HTTP basic Authentication only for API .antMatcher("/api/**").httpBasic() .and() //Login Form configuration for all others .formLogin().loginPage("/login").permitAll() .and() //Logout Form configuration .logout().permitAll();}
答案1
小编典典我的研究为我提供了解决方案:)
解
@Configuration@EnableWebMvcSecurity@EnableGlobalMethodSecurity(securedEnabled = true, prePostEnabled = true, proxyTargetClass = true)public class WebSecurityConfig extends WebSecurityConfigurerAdapter{ @Autowired private AuthenticationProvider authenticationProvider; @Autowired public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception { auth.authenticationProvider(authenticationProvider); } @Configuration @Order(1) public static class ApiWebSecurityConfig extends WebSecurityConfigurerAdapter{ @Override protected void configure(HttpSecurity http) throws Exception { http.csrf().disable() .antMatcher("/api/**") .authorizeRequests() .anyRequest().hasAnyRole("ADMIN", "API") .and() .httpBasic(); } } @Configuration @Order(2) public static class FormWebSecurityConfig extends WebSecurityConfigurerAdapter{ @Override public void configure(WebSecurity web) throws Exception { web.ignoring().antMatchers("/css/**", "/js/**", "/img/**", "/lib/**"); } @Override protected void configure(HttpSecurity http) throws Exception { http.csrf().disable() //HTTP with Disable CSRF .authorizeRequests() //Authorize Request Configuration .antMatchers("/connect/**").permitAll() .antMatchers("/", "/register").permitAll() .antMatchers("/admin/**").hasRole("ADMIN") .anyRequest().authenticated() .and() //Login Form configuration for all others .formLogin() .loginPage("/login").permitAll() .and() //Logout Form configuration .logout().permitAll(); } }}
AngularJS $Http CORS与Spring Rest&Security中的后端
web.xml中
<filter> <filter-name>springSecurityFilterChain</filter-name> <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
<filter-mapping> <filter-name>springSecurityFilterChain</filter-name> <url-pattern>/*</url-pattern>
<filter> <filter-name>cors</filter-name> <filter-class>com.axcessfinancial.web.filter.CorsFilter</filter-class>
<filter-mapping><filter-name>cors</filter-name><url-pattern>/*</url-pattern></filter-mapping>
上下文的security.xml
<http use-expressions="true"> <intercept-url pattern="/**" access="isAuthenticated()" /> <http-basic/> </http> <authentication-manager> <authentication-provider> <user-service> <user name="admin" password="admin" authorities="ROLE_USER" /> </user-service> </authentication-provider> </authentication-manager>
CorsFilter
protected void doFilterInternal(HttpServletRequest request,HttpServletResponse response,FilterChain filterChain) throws servletexception,IOException { response.addheader("Access-Control-Allow-Origin","*"); if (request.getHeader("Access-Control-Request-Method") != null && "OPTIONS".equals(request.getmethod())) { response.addheader("Access-Control-Allow-Methods","GET,POST,PUT,DELETE"); response.addheader("Access-Control-Allow-Headers","Authorization,Accept,Content-Type,X-PINGOTHER"); response.addheader("Access-Control-Max-Age","1728000"); } filterChain.doFilter(request,response); }
app.js
var app = angular.module('app',['app.controller','app.services']); app.config(function($httpProvider) { $httpProvider.defaults.useXDomain = true; delete $httpProvider.defaults.headers.common['X-Requested-With']; /* $httpProvider.defaults.headers.common['Authorization'] = 'Basic YWRtaW46YWRtaW4='; */ });
service.js
angular.module('app.services',[]).service('Service',function ($http,$q,UtilHttp) { $http.defaults.headers.common = {"Access-Control-Request-Headers": "accept,origin,authorization"}; $http.defaults.headers.common['Authorization'] = 'Basic YWRtaW46YWRtaW4='; return { listCutomer: function(){ var defer=$q.defer(); $http.post('http://localhost:8088/rest-template/soa/listCustomer',{withCredentials: true}) .success(function(data){ defer.resolve(data); }) .error(function(data){ defer.reject(data); }); return defer.promise; } }; });
问题:
Response Headersview source Content-Length 1134 Content-Type text/html;charset=utf-8 Date Wed,21 May 2014 14:39:44 GMT Server Apache-Coyote/1.1 Set-Cookie JSESSIONID=5CD90453C2CD57CE111F45B0FBCB0301; Path=/rest-template WWW-Authenticate Basic realm="Spring Security Application" Request Headers Accept text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8 Accept-Encoding gzip,deflate Accept-Language en-US,en;q=0.5 Access-Control-Request-He... authorization,content-type Access-Control-Request-Me... POST Cache-Control no-cache Connection keep-alive Host localhost:8088 Origin null Pragma no-cache User-Agent Mozilla/5.0 (Windows NT 6.1; WOW64; rv:24.0) Gecko/20100101 Firefox/24.0
解决方法
什么时候
>使用除GET或POST之外的HTTP动词
>需要发送自定义标头(例如,身份验证,X-API-Key等)
> need请求正文具有除text / plain之外的MIME类型
您的浏览器(遵循CORS规范)为请求添加了额外的步骤:
如果服务器响应批准您希望实际请求将启动的实际请求,它首先会向URL发送带有“OPTIONS”方法的特定请求.
不幸的是,在你的场景中,spring返回401(未授权)到OPTIONS请求,因为此请求中不存在auth令牌,因此你的真实请求永远不会启动
解:
你可以把你的cors过滤到web.xml中的spring安全过滤器之前,如果请求方法是OPTIONS,则避免调用链中的下一个过滤器(spring security)
这个exaple过滤器适合我:
public class SimpleCORSFilter implements Filter { public void doFilter(ServletRequest req,ServletResponse res,FilterChain chain) throws IOException,servletexception { HttpServletRequest request = (HttpServletRequest) req; HttpServletResponse response = (HttpServletResponse) res; response.setHeader("Access-Control-Allow-Credentials","true"); response.setHeader("Access-Control-Allow-Origin","*"); response.setHeader("Access-Control-Allow-Methods","POST,GET,DELETE,OPTIONS"); response.setHeader("Access-Control-Max-Age","3600"); response.setHeader("Access-Control-Allow-Headers","Origin,X-Requested-With,Authorization"); if ("OPTIONS".equalsIgnoreCase(request.getmethod())) { response.setStatus(HttpServletResponse.SC_OK); } else { chain.doFilter(req,res); } } public void init(FilterConfig filterConfig) { } public void destroy() { }
}
记得在web.xml中的spring安全过滤器之前声明你的cors过滤器
org.springframework.security.web.access.expression.DefaultWebSecurityExpressionHandler的实例源码
@Override public Object postProcessAfterInitialization(Object bean,String beanName) throws BeansException { // remove this if you are not using JSR-250 if(bean instanceof Jsr250MethodSecurityMetadataSource) { ((Jsr250MethodSecurityMetadataSource) bean).setDefaultRolePrefix(null); } if(bean instanceof DefaultMethodSecurityExpressionHandler) { ((DefaultMethodSecurityExpressionHandler) bean).setDefaultRolePrefix(null); } if(bean instanceof DefaultWebSecurityExpressionHandler) { ((DefaultWebSecurityExpressionHandler) bean).setDefaultRolePrefix(null); } if(bean instanceof SecurityContextHolderAwareRequestFilter) { ((SecurityContextHolderAwareRequestFilter)bean).setRolePrefix(""); } if(bean instanceof RoleVoter){ ((RoleVoter) bean).setRolePrefix(""); } return bean; }
@Override public Object postProcessAfterInitialization(Object bean,String beanName) throws BeansException { // remove this if you are not using JSR-250 if (bean instanceof Jsr250MethodSecurityMetadataSource) { ((Jsr250MethodSecurityMetadataSource) bean).setDefaultRolePrefix(this.rolePrefix); } if (bean instanceof DefaultMethodSecurityExpressionHandler) { ((DefaultMethodSecurityExpressionHandler) bean).setDefaultRolePrefix(this.rolePrefix); } if (bean instanceof DefaultWebSecurityExpressionHandler) { ((DefaultWebSecurityExpressionHandler) bean).setDefaultRolePrefix(this.rolePrefix); } if (bean instanceof SecurityContextHolderAwareRequestFilter) { ((SecurityContextHolderAwareRequestFilter) bean).setRolePrefix(this.rolePrefix); } return bean; }
@Override public Object postProcessAfterInitialization( Object bean,String beanName ) throws BeansException { if ( bean instanceof Jsr250MethodSecurityMetadataSource ) { ((Jsr250MethodSecurityMetadataSource) bean).setDefaultRolePrefix( null ); } if ( bean instanceof DefaultMethodSecurityExpressionHandler ) { ((DefaultMethodSecurityExpressionHandler) bean).setDefaultRolePrefix( null ); } if ( bean instanceof DefaultWebSecurityExpressionHandler ) { ((DefaultWebSecurityExpressionHandler) bean).setDefaultRolePrefix( null ); } if ( bean instanceof SecurityContextHolderAwareRequestFilter ) { ((SecurityContextHolderAwareRequestFilter) bean).setRolePrefix( "" ); } return bean; }
@Override public Object postProcessAfterInitialization(final Object bean,final String beanName) { if (bean instanceof DefaultMethodSecurityExpressionHandler) { ((DefaultMethodSecurityExpressionHandler) bean).setDefaultRolePrefix(null); } if (bean instanceof DefaultWebSecurityExpressionHandler) { ((DefaultWebSecurityExpressionHandler) bean).setDefaultRolePrefix(null); } if (bean instanceof SecurityContextHolderAwareRequestFilter) { SecurityContextHolderAwareRequestFilter filter = (SecurityContextHolderAwareRequestFilter) bean; filter.setRolePrefix(StringUtils.EMPTY); try { filter.afterPropertiesSet(); } catch (servletexception e) { throw new FatalBeanException(e.getMessage(),e); } } return bean; }
@Override public Object postProcessAfterInitialization(Object bean,String beanName) throws BeansException { // remove this if you are not using JSR-250 if (bean instanceof Jsr250MethodSecurityMetadataSource) { ((Jsr250MethodSecurityMetadataSource) bean).setDefaultRolePrefix(null); } if (bean instanceof DefaultMethodSecurityExpressionHandler) { ((DefaultMethodSecurityExpressionHandler) bean).setDefaultRolePrefix(null); } if (bean instanceof DefaultWebSecurityExpressionHandler) { ((DefaultWebSecurityExpressionHandler) bean).setDefaultRolePrefix(null); } if (bean instanceof SecurityContextHolderAwareRequestFilter) { ((SecurityContextHolderAwareRequestFilter) bean).setRolePrefix(""); } return bean; }
/** * JSP / Thymeleaf Permissions */ @Bean public DefaultWebSecurityExpressionHandler webExpressionHandler(){ return new DefaultWebSecurityExpressionHandler(){{ setPermissionEvaluator(permissionEvaluator()); }}; }
/** * Gets the {@link SecurityExpressionHandler} which is used for role hierarchy deFinition * * @return authenticationTokenFilter */ private SecurityExpressionHandler<FilterInvocation> expressionHandler() { DefaultWebSecurityExpressionHandler defaultWebSecurityExpressionHandler = new DefaultWebSecurityExpressionHandler(); defaultWebSecurityExpressionHandler.setRoleHierarchy(roleHierarchy()); return defaultWebSecurityExpressionHandler; }
@Override public void configure(WebSecurity web) throws Exception { web.expressionHandler(new DefaultWebSecurityExpressionHandler() { @Override protected SecurityExpressionoperations createSecurityExpressionRoot(Authentication authentication,FilterInvocation fi) { WebSecurityExpressionRoot root = (WebSecurityExpressionRoot) super.createSecurityExpressionRoot(authentication,fi); //root.setDefaultRolePrefix(""); //remove the prefix ROLE_ return root; } }); }
private SecurityExpressionHandler<FilterInvocation> webExpressionHandler() { DefaultWebSecurityExpressionHandler defaultWebSecurityExpressionHandler = new DefaultWebSecurityExpressionHandler(); defaultWebSecurityExpressionHandler.setDefaultRolePrefix(""); return defaultWebSecurityExpressionHandler; }
@Bean public SecurityExpressionHandler<FilterInvocation> webSecurityExpressionHandler(RoleHierarchy roleHierarchy) { final DefaultWebSecurityExpressionHandler handler = new CustomWebSecurityExpressionHandler(); handler.setRoleHierarchy(roleHierarchy); return handler; }
@Bean public DefaultWebSecurityExpressionHandler getWebExpressionHandler() { DefaultWebSecurityExpressionHandler handler = new DefaultWebSecurityExpressionHandler(); handler.setPermissionEvaluator(getPermissionEvaluator()); return handler; }
private SecurityExpressionHandler<FilterInvocation> webExpressionHandler() { DefaultWebSecurityExpressionHandler defaultWebSecurityExpressionHandler = new DefaultWebSecurityExpressionHandler(); defaultWebSecurityExpressionHandler.setRoleHierarchy(roleHierarchy); return defaultWebSecurityExpressionHandler; }
private SecurityExpressionHandler<FilterInvocation> webExpressionHandler() { DefaultWebSecurityExpressionHandler defaultWebSecurityExpressionHandler = new DefaultWebSecurityExpressionHandler(); defaultWebSecurityExpressionHandler.setRoleHierarchy(roleHierarchy()); return defaultWebSecurityExpressionHandler; }
@Bean public DefaultWebSecurityExpressionHandler webexpressionHandler(){ return new DefaultWebSecurityExpressionHandler(); }
private SecurityExpressionHandler<FilterInvocation> webExpressionHandler() { DefaultWebSecurityExpressionHandler handler = new DefaultWebSecurityExpressionHandler(); handler.setRoleHierarchy(roleHierarchy()); return handler; }
org.springframework.security.web.access.expression.WebSecurityExpressionRoot的实例源码
@Override protected SecurityExpressionoperations createSecurityExpressionRoot(final Authentication authentication,final FilterInvocation fi) { // There we use the extended version of expression manager final WebSecurityExpressionRoot root = new ExtendedWebSecurityExpressionRoot(authentication,fi); root.setPermissionEvaluator(getPermissionEvaluator()); root.setTrustResolver(trustResolver); root.setRoleHierarchy(getRoleHierarchy()); root.setDefaultRolePrefix("ROLE_"); return root; }
@Override protected SecurityExpressionoperations createSecurityExpressionRoot(Authentication authentication,FilterInvocation fi) { WebSecurityExpressionRoot root = new CustomWebSecurityExpressionRoot(authentication,fi); root.setPermissionEvaluator(getPermissionEvaluator()); root.setTrustResolver(new AuthenticationTrustResolverImpl()); root.setRoleHierarchy(getRoleHierarchy()); return root; }
@Override public void configure(WebSecurity web) throws Exception { web.expressionHandler(new DefaultWebSecurityExpressionHandler() { @Override protected SecurityExpressionoperations createSecurityExpressionRoot(Authentication authentication,FilterInvocation fi) { WebSecurityExpressionRoot root = (WebSecurityExpressionRoot) super.createSecurityExpressionRoot(authentication,fi); //root.setDefaultRolePrefix(""); //remove the prefix ROLE_ return root; } }); }
org.springframework.security.web.context.HttpRequestResponseHolder的实例源码
@Override protected void onSuccessfulAuthentication(HttpServletRequest request,HttpServletResponse response,Authentication authResult) { Object user=authResult.getPrincipal(); Assert.notNull(user,"通过Remember Me方式登录成功后未获取到用户信息"); HttpSession session=ContextHolder.getHttpSession(); IUser loginUser=null; if(user instanceof IUser){ loginUser=(IUser)user; }else if(user instanceof String){ loginUser=(IUser)userService.loadUserByUsername((String)user); }else{ throw new RuntimeException("Unsupport current principal["+user+"]"); } if(loginUser instanceof DefaultUser){ DefaultUser u=(DefaultUser)loginUser; u.setDepts(deptService.loadUserDepts(u.getUsername())); u.setPositions(positionService.loadUserPositions(u.getUsername())); u.setGroups(groupService.loadUserGroups(u.getUsername())); } session.setAttribute(ContextHolder.USER_LOGIN_WAY_KEY,"rememberMe"); session.setAttribute(ContextHolder.LOGIN_USER_SESSION_KEY,loginUser); this.doInterceptor(InterceptorType.success,new HttpRequestResponseHolder(request,response)); }
/** * Obtains the security context for the supplied request. For an unauthenticated user,an empty context * implementation should be returned. This method should not return null. * <p> * The use of the <tt>HttpRequestResponseHolder</tt> parameter allows implementations to return wrapped versions of * the request or response (or both),allowing them to access implementation-specific state for the request. * The values obtained from the holder will be passed on to the filter chain and also to the <tt>saveContext</tt> * method when it is finally called. Implementations may wish to return a subclass of * {@link SaveContextOnUpdateOrErrorResponseWrapper} as the response object,which guarantees that the context is * persisted when an error or redirect occurs. * * @param requestResponseHolder holder for the current request and response for which the context should be loaded. * * @return The security context which should be used for the current request,never null. */ @Override public SecurityContext loadContext(HttpRequestResponseHolder requestResponseHolder) { HttpServletRequest request = requestResponseHolder.getRequest(); HttpServletResponse response = requestResponseHolder.getResponse(); requestResponseHolder.setResponse(new SavetoCookieResponseWrapper(request,response)); Cookie authenticationCookie = getAuthenticationCookie(request); if (authenticationCookie == null) { return SecurityContextHolder.createEmptyContext(); } String serialisedAuthentication = tokenEncryption.decryptAndVerify(authenticationCookie.getValue()); if (serialisedAuthentication == null) { response.addCookie(createExpireAuthenticationCookie(request)); return SecurityContextHolder.createEmptyContext(); } Authentication authentication = authenticationSerializer.deserialize(serialisedAuthentication); SecurityContext securityContext = SecurityContextHolder.createEmptyContext(); securityContext.setAuthentication(authentication); return securityContext; }
@Test public void returnsSecurityContextWithAuthenticationForAuthenticatedRequest() throws Exception { TokenEncryption tokenEncryption = createJwtEncryption(); AuthenticationSerializer authenticationSerializer = new JsonAuthenticationSerializer(); CookieSecurityContextRepository repository = createCookieSecurityContextRepository(tokenEncryption,authenticationSerializer); UserDetails userDetails = new User("username","password",Collections.emptyList()); UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(userDetails,null,Collections.emptyList()); String serializedAuthentication = authenticationSerializer.serialize(authentication); String payload = tokenEncryption.encryptAndSign(serializedAuthentication); MockHttpServletRequest request = new MockHttpServletRequest(); request.setCookies(new Cookie(AUTHENTICATION_COOKIE_NAME,payload)); MockHttpServletResponse response = new MockHttpServletResponse(); SecurityContext securityContext = repository.loadContext(new HttpRequestResponseHolder(request,response)); assertthat(securityContext.getAuthentication(),notNullValue()); UserDetails authenticatedUserDetails = (UserDetails) securityContext.getAuthentication().getPrincipal(); assertthat(authenticatedUserDetails.getUsername(),equalTo(userDetails.getUsername())); }
@Test public void expireAuthenticationCookieForExpiredAuthToken() throws Exception { CookieSecurityContextRepository repository = createCookieSecurityContextRepository(); MockHttpServletRequest request = new MockHttpServletRequest(); request.setSecure(true); request.setCookies(new Cookie(AUTHENTICATION_COOKIE_NAME,"eyJjdHkiOiJKV1QiLCJlbmMiOiJBMjU2R0NNIiwiYWxnIjoiZGlyIn0..v3OyQykgTQI5U7gP.dKsmMKX1MHGoMx2rXrccwOCbyax-J8JS6gu63OBXEDm7Ab926OwlwlZcvoOZGW5nO7ZR95h2pe8pQs8s8cqWJUO4L4dGI9jTj4jK_Lsy9cPWDY4BMzs2bVBuasn88OQYjC-3zuZyvPKfQHrSVS9OjTaMLeMBwMfKP-k3IysOUfUtWUNcRb86v7VCnOd0ATljXUN8DekK8iZ0wD5AtBJVaOQLbaNWiXGY2pnA2eOW9cI_vPbCqqn4ZW-r7sEy6UzHgXYgRAr4bKb7abVtRvO1Xg3CcpquE597Om0bKJIk-VVCz7fVzpz5rkp16vzN-RKBJBs2MK-UsXKD9Lkgedh5w--Q4muiWrAqA5_Tx36mvkESlzR5pbsKu84ZweE5dfen47q_BWaZguVb8jFJB1pofpEgNiZ1C1K8aKIO03CIR-cOOfvoPrsdte-0M4F5bq4KwLna8fYm9D3OeJN3sai3Ba2KKPtLsfz-F5jJlCOV44JE-F9Pqa1xfdpD_S5UenWFi9IUsM912BoCTX4ouEMP6ZUVHwKgTeFjInJXe6iJVqvhPfrWUeVUBmBURy_8XGrzW12GqN_Qp_-275gQ_jlQfyMsdtkLdMp9YxpIbPb4Whq0ey5eKvy924Z4aWKQcw6SrVPAhFjXbvtwGVJYv2lzQ2vQIDE9g1dxqPpRvAG_qb_4M3Xfhtjo2W1Md-U1Oo5cfDsrbqeeegeYDH_AA5t5tJxLDB7TtR8xtjFb52WNItxcKeMnb6jegAwWlEjAkAqY.1d7Z0BNKOegXeUI_fY8yQg")); MockHttpServletResponse response = new MockHttpServletResponse(); HttpRequestResponseHolder requestResponseHolder = new HttpRequestResponseHolder(request,response); repository.loadContext(requestResponseHolder); ServletResponseWrapper responseWrapper = (ServletResponseWrapper) requestResponseHolder.getResponse(); MockHttpServletResponse wrappedResponse = (MockHttpServletResponse) responseWrapper.getResponse(); Cookie authenticationCookie = wrappedResponse.getCookie(AUTHENTICATION_COOKIE_NAME); assertthat(authenticationCookie.getMaxAge(),equalTo(0)); assertthat(authenticationCookie.getValue(),isEmptyString()); assertTrue(authenticationCookie.getSecure()); assertTrue(authenticationCookie.isHttpOnly()); }
@Test public void expireAuthenticationCookieForEmptySecurityContext() throws Exception { CookieSecurityContextRepository repository = createCookieSecurityContextRepository(); SecurityContext emptySecurityContext = SecurityContextHolder.createEmptyContext(); MockHttpServletRequest request = new MockHttpServletRequest(); request.setSecure(true); MockHttpServletResponse response = new MockHttpServletResponse(); HttpRequestResponseHolder requestResponseHolder = new HttpRequestResponseHolder(request,response); repository.loadContext(requestResponseHolder); repository.saveContext(emptySecurityContext,requestResponseHolder.getRequest(),requestResponseHolder.getResponse()); Cookie authenticationCookie = response.getCookie(AUTHENTICATION_COOKIE_NAME); assertthat(authenticationCookie.getMaxAge(),isEmptyString()); assertTrue(authenticationCookie.getSecure()); assertTrue(authenticationCookie.isHttpOnly()); }
@Test public void returnsSecurityContextWithAuthenticationForAuthenticatedRequest() throws Exception { CookieBasedSecurityContextRepository repository = createCookieBasedSecurityContextRepository(); JwtClientSerializer jwtClientSerializer = createJwtClientSerializer(); Client client = new Client("clientId","familyName","customerId",true,"unitId","serviceId","appointmentTypeId",true); String payload = jwtClientSerializer.serialize(client); MockHttpServletRequest request = new MockHttpServletRequest(); request.setCookies(new Cookie(SecurityContextSerializer.COOKIE_NAME,notNullValue()); Client authenticatedClient = (Client) securityContext.getAuthentication().getPrincipal(); assertthat(authenticatedClient.getClientId(),equalTo(client.getClientId())); }
@Test public void expireSessionCookieForExpiredAuthToken() throws Exception { CookieBasedSecurityContextRepository repository = createCookieBasedSecurityContextRepository(); MockHttpServletRequest request = new MockHttpServletRequest(); request.setSecure(true); request.setCookies(new Cookie(SecurityContextSerializer.COOKIE_NAME,response); repository.loadContext(requestResponseHolder); ServletResponseWrapper responseWrapper = (ServletResponseWrapper) requestResponseHolder.getResponse(); MockHttpServletResponse wrappedResponse = (MockHttpServletResponse) responseWrapper.getResponse(); Cookie sessionCookie = wrappedResponse.getCookie(SecurityContextSerializer.COOKIE_NAME); assertthat(sessionCookie.getMaxAge(),equalTo(0)); assertthat(sessionCookie.getValue(),isEmptyString()); assertTrue(sessionCookie.getSecure()); assertTrue(sessionCookie.isHttpOnly()); }
@Test public void addSessionCookieOnResponseForNonEmptySecurityContext() throws Exception { CookieBasedSecurityContextRepository repository = createCookieBasedSecurityContextRepository(); SecurityContext securityContext = SecurityContextHolder.createEmptyContext(); Client client = new Client("clientId",true); securityContext.setAuthentication(new UsernamePasswordAuthenticationToken(client,Collections.emptyList())); String payload = createJwtClientSerializer().serialize(client); MockHttpServletRequest request = new MockHttpServletRequest(); request.setSecure(true); request.setCookies(new Cookie(SecurityContextSerializer.COOKIE_NAME,payload)); MockHttpServletResponse response = new MockHttpServletResponse(); HttpRequestResponseHolder requestResponseHolder = new HttpRequestResponseHolder(request,response); repository.loadContext(requestResponseHolder); repository.saveContext(securityContext,requestResponseHolder.getResponse()); Cookie sessionCookie = response.getCookie(SecurityContextSerializer.COOKIE_NAME); assertthat(sessionCookie.getMaxAge(),equalTo(1800)); assertthat(sessionCookie.getValue().length(),greaterThan(0)); assertTrue(sessionCookie.getSecure()); assertTrue(sessionCookie.isHttpOnly()); }
@Test public void addCsrfCookieOnResponseForNonEmptySecurityContext() throws Exception { CookieBasedSecurityContextRepository repository = createCookieBasedSecurityContextRepository(); SecurityContext securityContext = SecurityContextHolder.createEmptyContext(); Client client = new Client("clientId",payload)); request.setCookies(new Cookie(CookieBasedCsrftokenRepository.CSRF_COOKIE_AND_ParaMETER_NAME,"csrftokenValue")); MockHttpServletResponse response = new MockHttpServletResponse(); HttpRequestResponseHolder requestResponseHolder = new HttpRequestResponseHolder(request,requestResponseHolder.getResponse()); Cookie csrfCookie = response.getCookie(CookieBasedCsrftokenRepository.CSRF_COOKIE_AND_ParaMETER_NAME); assertthat(csrfCookie.getMaxAge(),equalTo(1800)); assertthat(csrfCookie.getValue(),equalTo("csrftokenValue")); assertTrue(csrfCookie.getSecure()); assertTrue(csrfCookie.isHttpOnly()); }
@Test public void expireSessionCookieForEmptySecurityContext() throws Exception { CookieBasedSecurityContextRepository repository = createCookieBasedSecurityContextRepository(); SecurityContext emptySecurityContext = SecurityContextHolder.createEmptyContext(); MockHttpServletRequest request = new MockHttpServletRequest(); request.setSecure(true); MockHttpServletResponse response = new MockHttpServletResponse(); HttpRequestResponseHolder requestResponseHolder = new HttpRequestResponseHolder(request,isEmptyString()); assertTrue(sessionCookie.getSecure()); assertTrue(sessionCookie.isHttpOnly()); }
@RequestMapping(value = "/login",method = RequestMethod.POST) public @ResponseBody User login(@RequestBody User user,HttpServletRequest request,HttpServletResponse response) { User loginedUser = userService.sign(user.getUsername(),user.getpassword()); UsernamePasswordAuthenticationToken auth = new UsernamePasswordAuthenticationToken(loginedUser,user.getpassword(),loginedUser.getAuthorities()); auth.setDetails(loginedUser.getId()); SecurityContext context = SecurityContextHolder.getContext(); context.setAuthentication(auth); HttpRequestResponseHolder requestResponseHolder = new HttpRequestResponseHolder(request,response); sessionSecurityContextRepository.saveContext(context,requestResponseHolder.getResponse()); Long notification_count = notificationRepository.countByInBox(loginedUser.getInBox()); loginedUser.setNotificationCount(notification_count); return loginedUser; }
@Override public SecurityContext loadContext(HttpRequestResponseHolder requestResponseHolder) { String token = authStore.getToken(requestResponseHolder.getRequest(),authHeaderName); if(logger.isDebugEnabled()){ logger.debug("load context user token : {}",token); } if(StringUtils.isBlank(token)){ return SecurityContextHolder.createEmptyContext(); } SecurityContext context = SecurityContextHolder.getContext(); Authentication authentication = null; try { authentication = jwtTokenService.createAuthentication(token); } catch(CredentialsExpiredException e){ cookieStorer.clear(requestResponseHolder.getRequest(),requestResponseHolder.getResponse(),authHeaderName); } if(authentication!=null){ context.setAuthentication(authentication); } return context; }
@Override public SecurityContext loadContext(HttpRequestResponseHolder requestResponseHolder) { HttpServletRequest request = requestResponseHolder.getRequest(); HttpServletResponse response = requestResponseHolder.getResponse(); HttpSession httpSession = request.getSession(false); String sid = this.getSessionId(request,true); SecurityContext context = readSecurityContextFromSession(request); if (context == null) { context = SecurityContextHolder.createEmptyContext(); } SavetoSessionResponseWrapper wrappedResponse = new SavetoSessionResponseWrapper( response,request,httpSession != null,context,sid); requestResponseHolder.setResponse(wrappedResponse); if (isServlet3) { requestResponseHolder.setRequest(new Servlet3SavetoSessionRequestWrapper(request,wrappedResponse)); } return context; }
@Override public SecurityContext loadContext(HttpRequestResponseHolder requestResponseHolder) { wrapResponse(requestResponseHolder); LOGGER.debug("Trying to load security context from request."); Cookie securityCookie = getCookieForName(requestResponseHolder.getRequest().getCookies(),cookieName); if (securityCookie == null) { LOGGER.debug("No security cookie found in request. Returning empty context."); return createNewContext(); } LOGGER.debug("Security cookie found,trying to deserialize"); SecurityCookie cookie = securityCookieMarshaller.getSecurityCookie(securityCookie.getValue()); if (cookie == null || !cookie.isValid()) { LOGGER.debug("Security cookie was not valid. Returning empty context."); requestResponseHolder.getResponse().addCookie(createRemovalCookie()); return createNewContext(); } LOGGER.debug("Returning context from cookie."); SecurityContext context = cookie.getSecurityContext(); renewContext(context,requestResponseHolder); return context; }
final void save(SecurityContext securityContext,HttpServletRequest request) { HttpServletResponse response = new MockHttpServletResponse(); HttpRequestResponseHolder requestResponseHolder = new HttpRequestResponseHolder(request,response); this.repository.loadContext(requestResponseHolder); request = requestResponseHolder.getRequest(); response = requestResponseHolder.getResponse(); this.repository.saveContext(securityContext,response); }
public SecurityContext loadContext( HttpRequestResponseHolder requestResponseHolder) { SecurityContext securityContext = super .loadContext(requestResponseHolder); if (securityContext == null) { logger.debug("securityContext is null"); return null; } if (debug) { return securityContext; } SpringSecurityUserAuth userAuthInSession = SpringSecurityUtils .getCurrentUser(securityContext); if (userAuthInSession == null) { logger.debug("userAuthInSession is null"); return securityContext; } UserAuthDTO userAuthInCache = userAuthConnector.findById( userAuthInSession.getId(),userAuthInSession.getTenantId()); SpringSecurityUserAuth userAuthResult = new SpringSecurityUserAuth(); beanMapper.copy(userAuthInCache,userAuthResult); SpringSecurityUtils.saveUserDetailsToContext(userAuthResult,securityContext); return securityContext; }
@RequestMapping(value = "/login",method = RequestMethod.POST) public String login(HttpServletRequest request,Model model) { HttpRequestResponseHolder holder = new HttpRequestResponseHolder(request,response); httpSessionSecurityContextRepository.loadContext(holder); try { // 使用提供的证书认证用户 List<GrantedAuthority> authorities = AuthorityUtils.createAuthorityList("ROLE_USER","ROLE_ADMIN"); Authentication auth = new UsernamePasswordAuthenticationToken(request.getParameter("username"),request.getParameter("password"),authorities); SecurityContextHolder.getContext().setAuthentication(authenticationManager.authenticate(auth)); // 认证用户 if(!auth.isAuthenticated()) throw new CredentialException("用户不能够被认证"); } catch (Exception ex) { // 用户不能够被认证,重定向回登录页 logger.info(ex); return "login"; } // 从会话得到默认保存的请求 DefaultSavedRequest defaultSavedRequest = (DefaultSavedRequest) request.getSession().getAttribute("SPRING_Security_SAVED_REQUEST"); // 为令牌请求生成认证参数Map Map<String,String> authParams = getAuthParameters(defaultSavedRequest); AuthorizationRequest authRequest = new DefaultOAuth2RequestFactory(clientDetailsService).createAuthorizationRequest(authParams); authRequest.setAuthorities(AuthorityUtils.createAuthorityList("ROLE_USER","ROLE_ADMIN")); model.addAttribute("authorizationRequest",authRequest); httpSessionSecurityContextRepository.saveContext(SecurityContextHolder.getContext(),holder.getRequest(),holder.getResponse()); return "authorize"; }
@Override protected void additionalAuthenticationChecks(UserDetails userDetails,UsernamePasswordAuthenticationToken authentication) throws AuthenticationException { IUser user=(IUser)userDetails; HttpRequestResponseHolder holder=new HttpRequestResponseHolder(ContextHolder.getRequest(),ContextHolder.getResponse()); this.doInterceptor(InterceptorType.before,holder); try{ frameworkService.authenticate(user,authentication); }catch(Exception ex){ this.doInterceptor(InterceptorType.failure,holder); throw new AuthenticationServiceException(ex.getMessage()); } ContextHolder.getHttpSession().setAttribute(ContextHolder.LOGIN_USER_SESSION_KEY,user); this.doInterceptor(InterceptorType.success,holder); }
private void doInterceptor(InterceptorType type,HttpRequestResponseHolder holder){ for(ISecurityInterceptor intercepor:securityInterceptors){ if(type.equals(InterceptorType.before)){ intercepor.beforeLogin(holder); }else if(type.equals(InterceptorType.success)){ intercepor.loginSuccess(holder); }else if(type.equals(InterceptorType.failure)){ intercepor.loginFailure(holder); } } }
public void doFilter(ServletRequest request,ServletResponse response,FilterChain chain) throws IOException,servletexception { HttpRequestResponseHolder holder=new HttpRequestResponseHolder((HttpServletRequest)request,(HttpServletResponse)response); ContextHolder.setHttpRequestResponseHolder((HttpServletRequest)request,(HttpServletResponse)response); try{ this.doInterceptor(InterceptorType.before,holder); chain.doFilter(request,response); this.doInterceptor(InterceptorType.success,holder); }catch(Exception exception){ this.doInterceptor(InterceptorType.failure,holder); Throwable throwable=this.getThrowableCause(exception); boolean support=false; for(IExceptionHandler handler:exceptionHandlers){ if(handler.support(throwable)){ support=true; handler.handle(holder,throwable); break; } } if(!support){ if(throwable instanceof IOException){ throw (IOException)throwable; }else{ throw new servletexception(throwable); } } }finally{ ContextHolder.clean(); } }
private void doInterceptor(InterceptorType type,HttpRequestResponseHolder holder){ for(ISecurityInterceptor intercepor:securityInterceptors){ if(type.equals(InterceptorType.before)){ intercepor.beforeAuthorization(holder); }else if(type.equals(InterceptorType.success)){ intercepor.authorizationSuccess(holder); }else if(type.equals(InterceptorType.failure)){ intercepor.authorizationFailure(holder); } } }
private void doInterceptor(InterceptorType type,HttpRequestResponseHolder holder){ for(ISecurityInterceptor intercepor:securityInterceptors){ if(type.equals(InterceptorType.before)){ intercepor.beforeLogin(holder); }else if(type.equals(InterceptorType.success)){ intercepor.loginSuccess(holder); }else if(type.equals(InterceptorType.failure)){ intercepor.loginFailure(holder); } } }
@Override public SecurityContext loadContext(HttpRequestResponseHolder requestResponseHolder) { final String authToken = getToken(requestResponseHolder.getRequest()); if (authToken == null || hazelcastInstance.getMap("userTokenMap").get(authToken) == null) { logger.info("Returning empty securityContext"); return SecurityContextHolder.createEmptyContext(); } else { logger.info("Returning valid securityContext"); return (SecurityContext) hazelcastInstance.getMap("userTokenMap").get(authToken); } }
@Override public SecurityContext loadContext(HttpRequestResponseHolder requestResponseHolder) { final String authToken = getToken(requestResponseHolder.getRequest()); logger.debug("Reading security context token : " + authToken); if (authToken == null || hazelcastInstance.getMap("userTokenMap").get(authToken) == null) { logger.debug("Returning empty securityContext"); return SecurityContextHolder.createEmptyContext(); } else { logger.info("Returning valid securityContext"); return (SecurityContext) hazelcastInstance.getMap("userTokenMap").get(authToken); } }
@Test public void returnsEmptySecurityContextForUnauthenticatedRequest() throws Exception { CookieSecurityContextRepository repository = createCookieSecurityContextRepository(); MockHttpServletRequest request = new MockHttpServletRequest(); MockHttpServletResponse response = new MockHttpServletResponse(); SecurityContext securityContext = repository.loadContext(new HttpRequestResponseHolder(request,nullValue()); }
@Test public void returnsEmptySecurityContextForExpiredAuthToken() throws Exception { CookieSecurityContextRepository repository = createCookieSecurityContextRepository(); MockHttpServletRequest request = new MockHttpServletRequest(); request.setCookies(new Cookie(AUTHENTICATION_COOKIE_NAME,response); SecurityContext securityContext = repository.loadContext(requestResponseHolder); assertthat(securityContext.getAuthentication(),nullValue()); }
@Test public void addAuthenticationCookieOnResponseForNonEmptySecurityContext() throws Exception { TokenEncryption tokenEncryption = createJwtEncryption(); AuthenticationSerializer authenticationSerializer = new JsonAuthenticationSerializer(); CookieSecurityContextRepository repository = createCookieSecurityContextRepository(tokenEncryption,Collections.emptyList()); Authentication authentication = new UsernamePasswordAuthenticationToken(userDetails,Collections.emptyList()); SecurityContext securityContext = SecurityContextHolder.createEmptyContext(); securityContext.setAuthentication(authentication); String serializedAuthentication = authenticationSerializer.serialize(authentication); String payload = tokenEncryption.encryptAndSign(serializedAuthentication); MockHttpServletRequest request = new MockHttpServletRequest(); request.setSecure(true); request.setCookies(new Cookie(AUTHENTICATION_COOKIE_NAME,equalTo(AUTHENTICATION_COOKIE_MAX_AGE_SECONDS)); assertthat(authenticationCookie.getValue().length(),greaterThan(0)); assertTrue(authenticationCookie.getSecure()); assertTrue(authenticationCookie.isHttpOnly()); }
@Override public SecurityContext loadContext(HttpRequestResponseHolder requestResponseHolder) { SecurityContext context = SecurityContextHolder.createEmptyContext(); String token = tokenFromrequest(requestResponseHolder.getRequest()); Authentication authentication = PreAuthenticatedAuthenticationjsonWebToken.usingToken(token); if (authentication != null) { context.setAuthentication(authentication); logger.debug("Found bearer token in request. Saving it in SecurityContext"); } return context; }
@Test public void shouldLoadContextWithoutAuthenticationIfMissingAuthorizationHeader() throws Exception { BearerSecurityContextRepository repository = new BearerSecurityContextRepository(); HttpServletRequest request = mock(HttpServletRequest.class); HttpRequestResponseHolder holder = new HttpRequestResponseHolder(request,null); SecurityContext context = repository.loadContext(holder); assertthat(context,is(notNullValue())); assertthat(context.getAuthentication(),is(nullValue())); }
@Test public void shouldLoadContextWithoutAuthenticationIfInvalidAuthorizationHeaderValue() throws Exception { BearerSecurityContextRepository repository = new BearerSecurityContextRepository(); HttpServletRequest request = mock(HttpServletRequest.class); HttpRequestResponseHolder holder = new HttpRequestResponseHolder(request,null); when(request.getHeader("Authorization")).thenReturn("Bearer <Invalid>"); SecurityContext context = repository.loadContext(holder); assertthat(context,is(nullValue())); }
@Test public void shouldLoadContextWithoutAuthenticationIfEmptyAuthorizationHeaderValue() throws Exception { BearerSecurityContextRepository repository = new BearerSecurityContextRepository(); HttpServletRequest request = mock(HttpServletRequest.class); HttpRequestResponseHolder holder = new HttpRequestResponseHolder(request,null); when(request.getHeader("Authorization")).thenReturn("Bearer"); SecurityContext context = repository.loadContext(holder); assertthat(context,is(nullValue())); }
@Test public void shouldLoadContextWithoutAuthenticationIfAuthorizationHeaderValueNotBearerToken() throws Exception { BearerSecurityContextRepository repository = new BearerSecurityContextRepository(); HttpServletRequest request = mock(HttpServletRequest.class); HttpRequestResponseHolder holder = new HttpRequestResponseHolder(request,null); when(request.getHeader("Authorization")).thenReturn("Basic somevalue"); SecurityContext context = repository.loadContext(holder); assertthat(context,is(nullValue())); }
@Test public void shouldLoadContextWithAuthentication() throws Exception { String token = JWT.create() .sign(Algorithm.HMAC256("secret")); BearerSecurityContextRepository repository = new BearerSecurityContextRepository(); HttpServletRequest request = mock(HttpServletRequest.class); HttpRequestResponseHolder holder = new HttpRequestResponseHolder(request,null); when(request.getHeader("Authorization")).thenReturn("Bearer " + token); SecurityContext context = repository.loadContext(holder); assertthat(context,is(instanceOf(PreAuthenticatedAuthenticationjsonWebToken.class))); assertthat(context.getAuthentication().isAuthenticated(),is(false)); }
@Test public void returnsEmptySecurityContextForUnauthenticatedRequest() throws Exception { CookieBasedSecurityContextRepository repository = createCookieBasedSecurityContextRepository(); MockHttpServletRequest request = new MockHttpServletRequest(); MockHttpServletResponse response = new MockHttpServletResponse(); SecurityContext securityContext = repository.loadContext(new HttpRequestResponseHolder(request,nullValue()); }
@Test public void returnsEmptySecurityContextForExpiredAuthToken() throws Exception { CookieBasedSecurityContextRepository repository = createCookieBasedSecurityContextRepository(); MockHttpServletRequest request = new MockHttpServletRequest(); request.setCookies(new Cookie(SecurityContextSerializer.COOKIE_NAME,nullValue()); }
@Test public void addCsrfCookieOnResponSEOnUserLogin() throws Exception { CookieBasedCsrftokenRepository csrftokenRepository = new CookieBasedCsrftokenRepository(); CookieBasedSecurityContextRepository securityContextRepository = createCookieBasedSecurityContextRepository(csrftokenRepository); SecurityContext securityContext = SecurityContextHolder.createEmptyContext(); Client client = new Client("clientId",payload)); MockHttpServletResponse response = new MockHttpServletResponse(); Csrftoken token = csrftokenRepository.generatetoken(request); csrftokenRepository.savetoken(token,response); HttpRequestResponseHolder requestResponseHolder = new HttpRequestResponseHolder(request,response); securityContextRepository.loadContext(requestResponseHolder); securityContextRepository.saveContext(securityContext,requestResponseHolder.getResponse()); Cookie[] cookies = Arrays.stream(response.getCookies()).filter(cookie -> cookie.getName().equals(CookieBasedCsrftokenRepository.CSRF_COOKIE_AND_ParaMETER_NAME)).toArray(Cookie[]::new); assertthat(cookies.length,equalTo(1)); Cookie csrfCookie = cookies[0]; assertthat(csrfCookie.getMaxAge(),equalTo(token.getToken())); assertTrue(csrfCookie.getSecure()); assertTrue(csrfCookie.isHttpOnly()); }
@Override public Action inspect(AtmosphereResource r) { final SecurityContextRepository securityContextRepo = getSecurityContextRepository( r.getAtmosphereConfig().getServletContext()); if (securityContextRepo.containsContext(r.getRequest())) { LOGGER.trace("Loading the security context from the session"); final HttpRequestResponseHolder requestResponse = new HttpRequestResponseHolder(r.getRequest(),r.getResponse()); final SecurityContext securityContext = securityContextRepo.loadContext(requestResponse); SecurityContextHolder.setContext(securityContext); } return Action.CONTINUE; }
final void save(SecurityContext securityContext,response); }
final void save(SecurityContext securityContext,response); }
final void save(SecurityContext securityContext,response); repository.loadContext(requestResponseHolder); request = requestResponseHolder.getRequest(); response = requestResponseHolder.getResponse(); repository.saveContext(securityContext,response); }
今天关于用于Web的RESTFul和FormLogin和Cookies的Spring Security HTTP Basic-批注的分享就到这里,希望大家有所收获,若想了解更多关于AngularJS $Http CORS与Spring Rest&Security中的后端、org.springframework.security.web.access.expression.DefaultWebSecurityExpressionHandler的实例源码、org.springframework.security.web.access.expression.WebSecurityExpressionRoot的实例源码、org.springframework.security.web.context.HttpRequestResponseHolder的实例源码等相关知识,可以在本站进行查询。
本文标签: