美文网首页
spring boot 实例之 Oauth2

spring boot 实例之 Oauth2

作者: 碧波之心 | 来源:发表于2018-06-08 20:05 被阅读277次

    这节来完成spring oauth2功能的扩展。接前面的例子。

    引入组件

    引入spring-security-oauth2组件。

    <dependency>
        <groupId>org.springframework.security.oauth</groupId>
        <artifactId>spring-security-oauth2</artifactId>
        <version>2.3.3.RELEASE</version>
    </dependency>
    

    配置Oauth2服务器

    在com.biboheart.demo.user.security包中创建AuthorizationServerConfiguration,用来配置Oauth2服务

    package com.biboheart.demo.user.security;
    
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.beans.factory.annotation.Qualifier;
    import org.springframework.context.annotation.Bean;
    import org.springframework.context.annotation.Configuration;
    import org.springframework.security.authentication.AuthenticationManager;
    import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
    import org.springframework.security.crypto.password.PasswordEncoder;
    import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
    import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
    import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
    import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;
    import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer;
    import org.springframework.security.oauth2.provider.approval.ApprovalStore;
    import org.springframework.security.oauth2.provider.approval.TokenApprovalStore;
    
    @Configuration
    @EnableAuthorizationServer
    public class AuthorizationServerConfiguration extends AuthorizationServerConfigurerAdapter {
        @Autowired
        @Qualifier("authenticationManagerBean")
        private AuthenticationManager authenticationManager;
    
        @Override
        public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
            clients.inMemory()
                .withClient("client")
                .secret(new BCryptPasswordEncoder().encode("secret"))
                .authorizedGrantTypes("client_credentials", "password", "refresh_token", "authorization_code")
                .scopes("all")
                .autoApprove(true);
        }
        
        @Override
        public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
            endpoints
                .authenticationManager(this.authenticationManager);
        }
        
        @Override
        public void configure(AuthorizationServerSecurityConfigurer oauthServer)
                throws Exception {
            oauthServer
                .tokenKeyAccess("permitAll()")
                .checkTokenAccess("isAuthenticated()");
        }
        
        @Bean
        public ApprovalStore approvalStore() {
            TokenApprovalStore store = new TokenApprovalStore();
            return store;
        }
        
        @Bean
        public PasswordEncoder passwordEncoder() {
            return new BCryptPasswordEncoder();
        }
    
    }
    

    先使用内存客户端,后续再来转成数据库保存客户端。
    创建类ResourceConfiguration,用来配置资源服务

    package com.biboheart.demo.user.security;
    
    import org.springframework.context.annotation.Configuration;
    import org.springframework.security.config.annotation.web.builders.HttpSecurity;
    import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;
    import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter;
    
    @Configuration
    @EnableResourceServer
    public class ResourceConfiguration extends ResourceServerConfigurerAdapter {
        @Override
        public void configure(HttpSecurity http) throws Exception {
            http
                .anonymous().disable()
                .requestMatchers()
                    .antMatchers("/user/**")
                    .and()
                .authorizeRequests()
                    .antMatchers("/user/**").authenticated();
        }
    }
    

    创建MethodSecurityConfiguration类,用来开启函数的权限控制。可以在函数上面用注解的方式来判断权限。

    package com.biboheart.demo.user.security;
    
    import org.springframework.context.annotation.Configuration;
    import org.springframework.security.access.expression.method.MethodSecurityExpressionHandler;
    import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
    import org.springframework.security.config.annotation.method.configuration.GlobalMethodSecurityConfiguration;
    import org.springframework.security.oauth2.provider.expression.OAuth2MethodSecurityExpressionHandler;
    
    @Configuration
    @EnableGlobalMethodSecurity(prePostEnabled = true, proxyTargetClass = true)
    public class MethodSecurityConfiguration extends GlobalMethodSecurityConfiguration {
        @Override
        protected MethodSecurityExpressionHandler createExpressionHandler() {
            return new OAuth2MethodSecurityExpressionHandler();
        }
    }
    

    测试

    使用API工具(postman),测试获取access_token:
    生成Authorization


    Basic

    Headers:


    请求头
    获取token
    用户的token取到了。下一节来做个客户端来测试授权。

    相关文章

      网友评论

          本文标题:spring boot 实例之 Oauth2

          本文链接:https://www.haomeiwen.com/subject/eztzsftx.html