spring-security-oauth2注解详解
spring-security-oauth2支持的注解有:
1.EnableOAuth2Client
适用于使用spring security,并且想从Oauth2认证服务器来获取授权的web应用环境代码中,它启用了一个Oauth2 客户端配置。为了更好的利用这个特性,需要在客户端应用中的DelegatingFilterProxy(代理一个名为oauth2ClientContextFilter)增加一个servlet filter。当filter配置到client app时,可以使用注解@AccessTokenRequest提供的另一个bean来创建一个Oauth2RequestTemplate。示例:
@Configuration@EnableOAuth2Clientpublic class RemoteResourceConfiguration {@Beanpublic OAuth2RestOperations restTemplate(OAuth2ClientContext oauth2ClientContext) {return new OAuth2RestTemplate(remote(), oauth2ClientContext);}}
Client App使用client credential授权,不需要AccessTokenRequest或者域内RestOperation(对app来说,状态是全局的),但在需要时仍然使用filter来触发OAuth2RestOperation来获取token。使用密码授权的app需要在RestOperation动作之前为OAuth2ProtectedResouceDetail设置认证属性,这就是说,resouce detail 本身也需要session(假设系统中有多个用户)。
@Target(ElementType.TYPE) @Retention(RetentionPolicy.RUNTIME) @Documented @Import(OAuth2ClientConfiguration.class) public @interface EnableOAuth2Client {}
实现OAuth2ClientConfiguration
@Configuration public class OAuth2ClientConfiguration {@Beanpublic OAuth2ClientContextFilter oauth2ClientContextFilter() {OAuth2ClientContextFilter filter = new OAuth2ClientContextFilter();return filter;}@Bean@Scope(value = "request", proxyMode = ScopedProxyMode.INTERFACES)protected AccessTokenRequest accessTokenRequest(@Value("#{request.parameterMap}")Map<String, String[]> parameters, @Value("#{request.getAttribute('currentUri')}")String currentUri) {DefaultAccessTokenRequest request = new DefaultAccessTokenRequest(parameters);request.setCurrentUri(currentUri);return request;}@Configurationprotected static class OAuth2ClientContextConfiguration {@Resource@Qualifier("accessTokenRequest")private AccessTokenRequest accessTokenRequest;@Bean@Scope(value = "session", proxyMode = ScopedProxyMode.INTERFACES)public OAuth2ClientContext oauth2ClientContext() {return new DefaultOAuth2ClientContext(accessTokenRequest);}}}
2. EnableAuthorizationServer
工具方法,用来在当前应用context里(必须是一个DispatcherServlet context)开启一个授权server(例如AuthorizationEndpoint)和一个TokenEndpoint。server的多个属性可以通过自定义AuthorizationServerConfigurer类型(如AuthorizationServerConfigurerAdapter的扩展)的Bean来定制。通过正常使用spring security的特色EnableWebSecurity,用户负责保证授权Endpoint(/oauth/authorize)的安全,但Token Endpoint(/oauth/token)将自动使用http basic的客户端凭证来保证安全。通过一个或者多个AuthorizationServerConfigurer提供一个ClientDetailService来注册client(必须)。
@Target(ElementType.TYPE) @Retention(RetentionPolicy.RUNTIME) @Documented @Import({AuthorizationServerEndpointsConfiguration.class, AuthorizationServerSecurityConfiguration.class}) public @interface EnableAuthorizationServer {}
2.1 AuthorizationServerEndpointsConfiguration
private AuthorizationServerEndpointsConfigurer endpoints = new AuthorizationServerEndpointsConfigurer();@Autowiredprivate ClientDetailsService clientDetailsService;@Autowiredprivate List<AuthorizationServerConfigurer> configurers = Collections.emptyList();@PostConstructpublic void init() {for (AuthorizationServerConfigurer configurer : configurers) {try {configurer.configure(endpoints);} catch (Exception e) {throw new IllegalStateException("Cannot configure enpdoints", e);}}endpoints.setClientDetailsService(clientDetailsService);}
@Componentprotected static class TokenKeyEndpointRegistrar implements BeanDefinitionRegistryPostProcessor {private BeanDefinitionRegistry registry;@Overridepublic void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {String[] names = BeanFactoryUtils.beanNamesForTypeIncludingAncestors(beanFactory,JwtAccessTokenConverter.class, false, false);if (names.length > 0) {BeanDefinitionBuilder builder = BeanDefinitionBuilder.rootBeanDefinition(TokenKeyEndpoint.class);builder.addConstructorArgReference(names[0]);registry.registerBeanDefinition(TokenKeyEndpoint.class.getName(), builder.getBeanDefinition());}}@Overridepublic void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) throws BeansException {this.registry = registry;}}
2.2 AuthorizationServerSecurityConfiguration
@Configuration @Order(0) @Import({ ClientDetailsServiceConfiguration.class, AuthorizationServerEndpointsConfiguration.class }) public class AuthorizationServerSecurityConfiguration extends WebSecurityConfigurerAdapter {@Autowiredprivate List<AuthorizationServerConfigurer> configurers = Collections.emptyList();@Autowiredprivate ClientDetailsService clientDetailsService;@Autowiredprivate AuthorizationServerEndpointsConfiguration endpoints;@Autowiredpublic void configure(ClientDetailsServiceConfigurer clientDetails) throws Exception {for (AuthorizationServerConfigurer configurer : configurers) {configurer.configure(clientDetails);}}@Overrideprotected void configure(AuthenticationManagerBuilder auth) throws Exception {// Over-riding to make sure this.disableLocalConfigureAuthenticationBldr = false// This will ensure that when this configurer builds the AuthenticationManager it will not attempt// to find another 'Global' AuthenticationManager in the ApplicationContext (if available),// and set that as the parent of this 'Local' AuthenticationManager.// This AuthenticationManager should only be wired up with an AuthenticationProvider// composed of the ClientDetailsService (wired in this configuration) for authenticating 'clients' only. }@Overrideprotected void configure(HttpSecurity http) throws Exception {AuthorizationServerSecurityConfigurer configurer = new AuthorizationServerSecurityConfigurer();FrameworkEndpointHandlerMapping handlerMapping = endpoints.oauth2EndpointHandlerMapping();http.setSharedObject(FrameworkEndpointHandlerMapping.class, handlerMapping);configure(configurer);http.apply(configurer);String tokenEndpointPath = handlerMapping.getServletPath("/oauth/token");String tokenKeyPath = handlerMapping.getServletPath("/oauth/token_key");String checkTokenPath = handlerMapping.getServletPath("/oauth/check_token");if (!endpoints.getEndpointsConfigurer().isUserDetailsServiceOverride()) {UserDetailsService userDetailsService = http.getSharedObject(UserDetailsService.class);endpoints.getEndpointsConfigurer().userDetailsService(userDetailsService);}// @formatter:off http.authorizeRequests().antMatchers(tokenEndpointPath).fullyAuthenticated().antMatchers(tokenKeyPath).access(configurer.getTokenKeyAccess()).antMatchers(checkTokenPath).access(configurer.getCheckTokenAccess()).and().requestMatchers().antMatchers(tokenEndpointPath, tokenKeyPath, checkTokenPath).and().sessionManagement().sessionCreationPolicy(SessionCreationPolicy.NEVER);// @formatter:onhttp.setSharedObject(ClientDetailsService.class, clientDetailsService);}protected void configure(AuthorizationServerSecurityConfigurer oauthServer) throws Exception {for (AuthorizationServerConfigurer configurer : configurers) {configurer.configure(oauthServer);}}}
3. EnableResourceServer
Oauth2 资源服务器的便利方法,开启了一个spring security的filter,这个filter通过一个Oauth2的token进行认证请求。使用者应该增加这个注解,并提供一个ResourceServerConfigurer类型的Bean(例如通过ResouceServerConfigurerAdapter)来指定资源(url路径和资源id)的细节。为了利用这个filter,你必须在你的应用中的某些地方EnableWebSecurity,或者使用这个注解的地方,或者其他别的地方。
这个注解创建了一个WebSecurityConfigurerAdapter,且自带了硬编码的order=3.在spring中,由于技术原因不能立即改变order的顺序,因此你必须在你的spring应用中避免使用order=3的其他WebSecurityConfigurerAdapter。
@Target(ElementType.TYPE) @Retention(RetentionPolicy.RUNTIME) @Documented @Import(ResourceServerConfiguration.class) public @interface EnableResourceServer {}
ResourceServerConfiguration
@Overrideprotected void configure(HttpSecurity http) throws Exception { ResourceServerSecurityConfigurer resources = new ResourceServerSecurityConfigurer();ResourceServerTokenServices services = resolveTokenServices();if (services != null) {resources.tokenServices(services);}else {if (tokenStore != null) {resources.tokenStore(tokenStore);}else if (endpoints != null) {resources.tokenStore(endpoints.getEndpointsConfigurer().getTokenStore());}}if (eventPublisher != null) {resources.eventPublisher(eventPublisher);}for (ResourceServerConfigurer configurer : configurers) {configurer.configure(resources);}// @formatter:offhttp.authenticationProvider(new AnonymousAuthenticationProvider("default"))// N.B. exceptionHandling is duplicated in resources.configure() so that// it works .exceptionHandling().accessDeniedHandler(resources.getAccessDeniedHandler()).and().sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).and().csrf().disable();// @formatter:on http.apply(resources);if (endpoints != null) {// Assume we are in an Authorization Serverhttp.requestMatcher(new NotOAuthRequestMatcher(endpoints.oauth2EndpointHandlerMapping()));}for (ResourceServerConfigurer configurer : configurers) {// Delegates can add authorizeRequests() here configurer.configure(http);}if (configurers.isEmpty()) {// Add anyRequest() last as a fall back. Spring Security would// replace an existing anyRequest() matcher with this one, so to// avoid that we only add it if the user hasn't configured anything. http.authorizeRequests().anyRequest().authenticated();}}
ResourceServerSecurityConfigurer
重新的两个方法
1.init
@Overridepublic void init(HttpSecurity http) throws Exception {registerDefaultAuthenticationEntryPoint(http);}@SuppressWarnings("unchecked")private void registerDefaultAuthenticationEntryPoint(HttpSecurity http) {ExceptionHandlingConfigurer<HttpSecurity> exceptionHandling = http.getConfigurer(ExceptionHandlingConfigurer.class);if (exceptionHandling == null) {return;}ContentNegotiationStrategy contentNegotiationStrategy = http.getSharedObject(ContentNegotiationStrategy.class);if (contentNegotiationStrategy == null) {contentNegotiationStrategy = new HeaderContentNegotiationStrategy();}MediaTypeRequestMatcher preferredMatcher = new MediaTypeRequestMatcher(contentNegotiationStrategy,MediaType.APPLICATION_ATOM_XML, MediaType.APPLICATION_FORM_URLENCODED, MediaType.APPLICATION_JSON,MediaType.APPLICATION_OCTET_STREAM, MediaType.APPLICATION_XML, MediaType.MULTIPART_FORM_DATA,MediaType.TEXT_XML);preferredMatcher.setIgnoredMediaTypes(Collections.singleton(MediaType.ALL));exceptionHandling.defaultAuthenticationEntryPointFor(postProcess(authenticationEntryPoint), preferredMatcher);}
2.configure
@Overridepublic void configure(HttpSecurity http) throws Exception {AuthenticationManager oauthAuthenticationManager = oauthAuthenticationManager(http);resourcesServerFilter = new OAuth2AuthenticationProcessingFilter();resourcesServerFilter.setAuthenticationEntryPoint(authenticationEntryPoint);resourcesServerFilter.setAuthenticationManager(oauthAuthenticationManager);if (eventPublisher != null) {resourcesServerFilter.setAuthenticationEventPublisher(eventPublisher);}if (tokenExtractor != null) {resourcesServerFilter.setTokenExtractor(tokenExtractor);}resourcesServerFilter = postProcess(resourcesServerFilter);resourcesServerFilter.setStateless(stateless);// @formatter:off http.authorizeRequests().expressionHandler(expressionHandler).and().addFilterBefore(resourcesServerFilter, AbstractPreAuthenticatedProcessingFilter.class).exceptionHandling().accessDeniedHandler(accessDeniedHandler).authenticationEntryPoint(authenticationEntryPoint);// @formatter:on}
其中OAuth2AuthenticationProcessingFilter:A pre-authentication filter for OAuth2 protected resources. Extracts an OAuth2 token from the incoming request and uses it to populate the Spring Security context with an {@link OAuth2Authentication} (if used in conjunction with an{@link OAuth2AuthenticationManager}).
转载于:https://www.cnblogs.com/davidwang456/p/6480681.html
spring-security-oauth2注解详解相关推荐
- Spring Cache常用注解详解
Spring Cache常用注解详解 @EnableCaching 开启Spring Cache框架支持.解析对应的注解,实现缓存读写访问 @CacheConfig 缓存配置,可以配置当前类型中所用缓 ...
- Spring Security 认证授权详解
1.Spring Security 概述 1.1.Spring Security 简介 Spring Security 是 Spring 家族中的成员.Spring Security 基于 Sprin ...
- Spring定时任务 - @Schedule注解详解
一.@Schedule注解一览 @Scheduled注解共有8个属性(其中有3组只是不同类型的相同配置)和一个常量CRON_DISABLED,源码如下: /*** 标记要调度的方法的注释. 必须准确指 ...
- Spring Security 的 RememberMe 详解 !!!!!
目录 目录 一.介绍 二.基本使用 2.1 开启记住我 三.原理分析 3.1 页面参数 3.2 RememberMeServices 3.3 TokenBasedRememberMeServices ...
- Spring中@Value注解详解
在spring项目中必不可少的就是读取配置文件,那么读取配置文件就有两种方式.一种就是使用Spring中@Value注解,还有一种是使用SpringBoot中的@ConfigurationProper ...
- Spring框架@PostConstruct注解详解
文章目录 前言 业务背景 通过依赖查找实现 `@PostConstruct`注解实现 @PostConstruct注解原理 `@PostConstruct`注解 `@PostConstruct`注解源 ...
- spring mvc -@RequestMapping注解详解
https://www.cnblogs.com/caoyc/p/5635173.html @RequestMapping参数说明: value:定义处理方法的请求的URL地址(重点): method: ...
- Spring MVC @RequestMapping注解详解
@RequestMapping 参数说明 value:定义处理方法的请求的 URL 地址.(重点) method:定义处理方法的 http method 类型,如 GET.POST 等.(重点) pa ...
- spring mvc 常用注解详解
@Controller 在SpringMVC 中,控制器Controller 负责处理由DispatcherServlet 分发的请求,它把用户请求的数据经过业务处理层处理之后封装成一个Model , ...
- spring定时任务@Scheduled注解详解
1.@Scheduled注解 常见参数: 1.fixedRate参数,传入一个时间间隔,单位是毫秒,这里是指每5s执行一次 @Scheduled(fixedRate = 5000)public voi ...
最新文章
- 2017年7月十三日正式开始记录
- python编程设计_Python程序设计
- 【已解决】可以访问Tomcat下webapp中的文件目录(间接实现下载功能)
- [转] apache配置rewrite及.htaccess文件
- 活久见,自己创造的框架竟然比开源的好用
- html实现验证码效果,js实现验证码功能
- 谷歌终于拒绝 AI 武器化了!
- js原生ajax跨域请求,封装一个原生js的ajax请求,支持IE9CORS跨域请求
- SVN仓库解决APIcloud2检出错误
- JAVA游戏死神之谜下载_诸神战纪二-死神之谜BT版
- canvas卡通兔子萝卜飞行动画
- 计算机毕业设计ssm鲲龙装饰公司在线管理系统的设计与开发前台模块iub6h系统+程序+源码+lw+远程部署
- shell之awk命令详解
- Compilation error 未完待续
- 证明完全立方数模9同余_牡丹江2立方玻璃钢蓄水池报价
- java httpget 传参数_Java 发送http请求(get、post)
- JavaBean输入圆的半径,求圆的面积和周长
- 深度学习中的Epoch,Batchsize,Iterations深刻理解
- 关于常用 软件授权 Licence说明
- vue单页面设置高度100%全屏
热门文章
- linux开发常用脚本,记录自己常用的一些 Linux Shell 脚本
- mysql 日志的存放形式_mysql日志详细解析
- 关闭linux远程桌面,[Linux]Ubuntu 16.04 远程桌面(简单暴力)
- ug怎么画曲线_UG怎么画雨伞的曲面造型
- mysql读写分离实例_SpringBoot+MyBatis+MySQL读写分离(实例)
- python中multiindex如何索引_python – MultiIndex DataFrames的Pandas HDFStore:如何有效地获取所有索引...
- clear java_Java ConcurrentLinkedDeque clear()用法及代码示例
- python制表符什么意思_python中制表符是什么意思
- 简单回声服务器的实现
- rdd数据存内存 数据量_spark系列:spark core 数据交互技术点(数据模型)