zoukankan      html  css  js  c++  java
  • OAuth2.0-1

    分布式授权解决方案:

     其中授权服务一般放在网关服务上,资源服务指的是,挂在网关下得各个微服务

      网关授权客户端》客户端拿到token》客户端拿到token到网关验证,获取token明文》各个资源端拿着token明文放到security得上下文中访问相应得资源

     

    授权服务配置:

    /**
     * 授权服务配置
     */
    @Configuration
    //开启oauth2,auth server模式
    @EnableAuthorizationServer
    public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {

     

     

     客户端详情服务类似于userdetailservice;一个针对客户,一个针对客户端

    这3步的配置代码:

    package lee.config;
    
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.context.annotation.Bean;
    import org.springframework.context.annotation.Configuration;
    import org.springframework.http.HttpMethod;
    import org.springframework.security.authentication.AuthenticationManager;
    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.ClientDetailsService;
    import org.springframework.security.oauth2.provider.code.InMemoryAuthorizationCodeServices;
    import org.springframework.security.oauth2.provider.token.AuthorizationServerTokenServices;
    import org.springframework.security.oauth2.provider.token.DefaultTokenServices;
    import org.springframework.security.oauth2.provider.token.TokenStore;
    
    @Configuration
    
    //开启oauth2,auth server模式
    @EnableAuthorizationServer
    public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {
    
        @Autowired
        private PasswordEncoder passwordEncoder;
    
        //配置客户端
    
        /**1.配置客户端,允许哪些客户端来调用服务
         * 类似于userdetailservice 用来查询客户端详情信息的
         * @param clients
         * @throws Exception
         */
        @Override
        public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
            clients.inMemory()
                    //client的id和密码
                    .withClient("client1")
                    .secret(passwordEncoder.encode("123123"))
    
                    //给client一个id,这个在client的配置里要用的
                    .resourceIds("resource1")
    
                    //允许的申请token的方式,测试用例在test项目里都有.
                    //authorization_code授权码模式,这个是标准模式
                    //implicit简单模式,这个主要是给无后台的纯前端项目用的
                    //password密码模式,直接拿用户的账号密码授权,不安全
                    //client_credentials客户端模式,用clientid和密码授权,和用户无关的授权方式
                    //refresh_token使用有效的refresh_token去重新生成一个token,之前的会失效
                    .authorizedGrantTypes("authorization_code", "password", "client_credentials", "implicit", "refresh_token")
    
                    //授权的范围,每个resource会设置自己的范围.
                    .scopes("scope1", "scope2")
    
                    //这个是设置要不要弹出确认授权页面的.
                    .autoApprove(false)
    
                    //这个相当于是client的域名,重定向给code的时候会跳转这个域名
                    .redirectUris("http://www.baidu.com");
    
                    /*.and()
    
                    .withClient("client2")
                    .secret(passwordEncoder.encode("123123"))
                    .resourceIds("resource1")
                    .authorizedGrantTypes("authorization_code", "password", "client_credentials", "implicit", "refresh_token")
                    .scopes("all")
                    .autoApprove(false)
                    .redirectUris("http://www.qq.com");*/
        }
    
    
        @Autowired
        private ClientDetailsService clientDetailsService;
    
        @Autowired
        private TokenStore tokenStore;
    
        //配置token管理服务
        @Bean
        public AuthorizationServerTokenServices tokenServices() {
            DefaultTokenServices defaultTokenServices = new DefaultTokenServices();
            defaultTokenServices.setClientDetailsService(clientDetailsService);
            defaultTokenServices.setSupportRefreshToken(true);
    
            //配置token的存储方法
            defaultTokenServices.setTokenStore(tokenStore);
            defaultTokenServices.setAccessTokenValiditySeconds(300);
            defaultTokenServices.setRefreshTokenValiditySeconds(1500);
            return defaultTokenServices;
        }
    
        //密码模式才需要配置,认证管理器
        @Autowired
        private AuthenticationManager authenticationManager;
    
        //把上面的各个组件组合在一起
    
        /**2.配置令牌怎么生成令牌怎么存储令牌等
         * 配置令牌访问端点和令牌服务。其实就是配置令牌访问的url
         * @param endpoints
         * @throws Exception
         */
        @Override
        public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
            endpoints.authenticationManager(authenticationManager)//认证管理器
                    .authorizationCodeServices(new InMemoryAuthorizationCodeServices())//授权码管理
                    .tokenServices(tokenServices())//token管理
                    .allowedTokenEndpointRequestMethods(HttpMethod.POST);
        }
    
        //配置哪些接口可以被访问
    
        /**3.配置令牌端点安全约束,不是任何人都能来申请令牌的(例子里我们放开了限制)
         * 类似于
         * .antMatchers("/manager/index").hasAnyAuthority("Role_List")
         * @param security
         * @throws Exception
         */
        @Override
        public void configure(AuthorizationServerSecurityConfigurer security) throws Exception {
            security.tokenKeyAccess("permitAll()")///oauth/token_key公开
                    .checkTokenAccess("permitAll()")///oauth/check_token公开
                    .allowFormAuthenticationForClients();//允许表单认证
        }
    }

     

     

    @Configuration
    public class TokenConfig {
    
        //配置token的存储方法
        @Bean
        public TokenStore tokenStore() {
            //配置token存储在内存中,这种是普通token,每次都需要远程校验,性能较差
            return new InMemoryTokenStore();
        }
    }

        @Autowired
        private TokenStore tokenStore;
        //配置token管理服务
        @Bean
        public AuthorizationServerTokenServices tokenServices() {
            DefaultTokenServices defaultTokenServices = new DefaultTokenServices();
            defaultTokenServices.setClientDetailsService(clientDetailsService);
            defaultTokenServices.setSupportRefreshToken(true);//支持刷新令牌
            defaultTokenServices.setTokenStore(tokenStore); //配置token的存储方法-例子采用内存存储
            defaultTokenServices.setAccessTokenValiditySeconds(300); //令牌有效期
            defaultTokenServices.setRefreshTokenValiditySeconds(1500); //刷新令牌有效期 默认3天
            return defaultTokenServices;
        }

    此服务配置注入在授权服务AuthorizationServerConfig里

     

     

     

     

     代码如下:

    package lee.config;
    
    import lee.model.MyUserDetails;
    import org.springframework.context.annotation.Bean;
    import org.springframework.context.annotation.Configuration;
    import org.springframework.security.authentication.AuthenticationManager;
    import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
    import org.springframework.security.config.annotation.web.builders.HttpSecurity;
    import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
    import org.springframework.security.core.userdetails.User;
    import org.springframework.security.core.userdetails.UserDetailsService;
    import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
    import org.springframework.security.crypto.password.PasswordEncoder;
    import org.springframework.security.provisioning.InMemoryUserDetailsManager;
    
    @Configuration
    @EnableGlobalMethodSecurity(securedEnabled = true, prePostEnabled = true)
    public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
    
        @Bean
        public PasswordEncoder passwordEncoder() {
            return new BCryptPasswordEncoder();
        }
    
        //密码模式才需要配置,认证管理器
        @Bean
        @Override
        protected AuthenticationManager authenticationManager() throws Exception {
            return super.authenticationManager();
        }
    
        @Override
        protected void configure(HttpSecurity http) throws Exception {
            http.csrf().disable()
                    .authorizeRequests()
                    .anyRequest().permitAll()
    
                    .and()
                    .formLogin()
    
                    .and()
                    .logout();
        }
    
        @Override
        @Bean
        public UserDetailsService userDetailsService() {
            /**
             * 基于内存创建用户
             */
            InMemoryUserDetailsManager manager=new InMemoryUserDetailsManager();
    
            manager.createUser(User.withUsername("zhangsan").password(passwordEncoder().encode("123")).authorities("admin").build());
            manager.createUser(User.withUsername("lisi").password(passwordEncoder().encode("123")).authorities("user").build());
            return manager;
    /*
            return s -> {
                if ("admin".equals(s) || "user".equals(s)) {
                    return new MyUserDetails(s, passwordEncoder().encode(s), s);
                }
                return null;
            };*/
        }
    }

    至此授权服务就已经搭建好了;下面我们进行测试一下:

    一、授权服务

    1.授权码模式 

     

       1.1浏览器访问

      http://127.0.0.1:9001/oauth/authorize?client_id=client1&response_type=code&scope=scope1&redirect_uri=http://www.baidu.com

      这代表我的页面(假如我的页面是百度)需要用9001的服务器进行登录(就像很多页面可以用QQ登陆一样)

      这时候会跳转到9001的登录页面:

       登录后,会跳转授权页面给该app授权,授权后会在重定向的页面带上授权码:

     

     1.2拿到授权码后可以用授权码、之前在9001申请的appId和secret去获取令牌

    postman 访问:         http://127.0.0.1:9001/oauth/token?client_id=client1&client_secret=123123&grant_type=authorization_code&code=8cUIKC&redirect_uri=http://www.baidu.com

     

     刷新令牌:当访问令牌无效的时候可以用刷新令牌重新去申请访问令牌;

     2.简化模式

      浏览器访问

      http://127.0.0.1:9001/oauth/authorize?client_id=client1&response_type=token&scope=scope1&redirect_uri=http://www.baidu.com

      返回如下:

    重定向连接会直接带上token信息:

    https://www.baidu.com/#access_token=96b73bb0-40f8-4fdb-b207-42ce15ae01be&token_type=bearer&expires_in=299

    简化模式用于没有服务器端的第三方单页面应用,因为没有服务器就无法接受授权码。

    3.密码模式

      该模式会将密码泄露给客户端,所以这种模式只能用于client是我们自己开发的情况下,因此密码模式一般用于我们自己开发的第一方原生app。

      http://127.0.0.1:9001/oauth/token?client_id=client1&client_secret=123123&grant_type=password&username=user&password=user

      直接申请返回令牌:

     

    4.客户端模式

     

      http://127.0.0.1:9001/oauth/token?client_id=client1&client_secret=123123&grant_type=client_credentials

      只需要client_id、client_secret 和grant_type授权类型即可申请令牌

      Postman调用如下:

      该模式用于在我们完全信任客户端的情况下,而client也是安全的;比如合作方对接,拉取一组用户信息。或者系统内部调用。

    二、资源服务配置

    /**
     * 资源服务配置
     */
    @Configuration
    //开启oauth2,reousrce server模式
    @EnableResourceServer
    public class ResourceServerConfig extends ResourceServerConfigurerAdapter {

     

     以上配置得代码:

    /**
     * 资源服务配置
     */
    @Configuration
    //开启oauth2,reousrce server模式
    @EnableResourceServer
    public class ResourceServerConfig extends ResourceServerConfigurerAdapter {
        public static final String RESOURCE_ID="resource1";//资源id
        @Override
        public void configure(ResourceServerSecurityConfigurer resources) throws Exception {
            resources
                    //设置我这个resource的id, 这个在auth中配置, 这里必须照抄
                    .resourceId(RESOURCE_ID)//该资源id
                    .tokenServices(tokenServices())
                    //这个貌似是配置要不要把token信息记录在session中
                    .stateless(true);
        }
    
        /**
         * 配置资源访问规则
         * @param http
         * @throws Exception
         */
        @Override
        public void configure(HttpSecurity http) throws Exception {
            http.csrf().disable()
                    .authorizeRequests()
                    //本项目所需要的授权范围,这个scope是写在auth服务的配置里的
                    .antMatchers("/**").access("#oauth2.hasScope('scope1')")
                    .and()
                    //配置要不要把token信息记录在session中
                    .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
        }
    
        /**
         * 令牌验证服务
         * @return
         */
        @Bean
        public RemoteTokenServices tokenServices(){
            //远程token验证, 普通token必须远程校验
            RemoteTokenServices services = new RemoteTokenServices();
            //配置去哪里验证token
            services.setCheckTokenEndpointUrl("http://127.0.0.1:9001/oauth/check_token");
            //配置组件的clientid和密码,这个也是在auth中配置好的
            services.setClientId("client1");
            services.setClientSecret("123123");
            return services;
        }
    }

    配置资源

    @RestController
    public class IndexController {
    
        @RequestMapping("user")
        @PreAuthorize("hasAnyAuthority('user')")
        public String user() {
            return "user";
        }
    
        //测试接口
        @RequestMapping("admin")
        @PreAuthorize("hasAnyAuthority('admin')")
        public String admin() {
            return "admin";
        }
    
        @RequestMapping("me")
        public Principal me(Principal principal) {
            return principal;
        }
    }

     另外还要配置安全访问控制WebSecurityConfig 才能使权限生效:

     由于资源是基于方法得授权,基于web得授权就可以屏蔽掉了

    @Configuration
    @EnableGlobalMethodSecurity(securedEnabled = true, prePostEnabled = true)
    public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
    
        //安全拦截机制
        @Override
        protected void configure(HttpSecurity http) throws Exception {
            http.csrf().disable()
                    //由于拦截的是接口方法无需配置拦截url 只需要在controller配置即可
                    .authorizeRequests()
                    .anyRequest().permitAll();
        }
    }

      校验令牌:http://127.0.0.1:9001/oauth/check_token

       校验令牌会带回所有有用户所有权限信息,资源服务拿到这些权限信息后可以去申请相应得资源

       带令牌访问资源:

      需要在header里面带入令牌:Key:” Authorization” value:” Bearer+空格+token”

     实际工作应用:若要用授权码模式  需要事先给定客户端一个 权限编码 并且在调用方法得时候  验证这个权限编码是否有权限调用接口

            如果用账号密码模式 道理也一样

    JWT令牌见下一章:

  • 相关阅读:
    Android记事本05
    Android记事本开发04
    Android记事本开发03
    Android记事本开发02
    Android记事本开发01
    项目目标文档
    利益相关者描述案例
    《软件需求》阅读笔记03
    《软件需求》阅读笔记02
    《软件需求》阅读笔记01
  • 原文地址:https://www.cnblogs.com/jiawen010/p/12974380.html
Copyright © 2011-2022 走看看