OAuth 2认证模式 - 授权码模式(authorization code)


Oauth2认证模式 - 授权码模式(authorization code)

1. 交互流程

交互流程如下

2. 实现步骤

实现 oauth2 需要三个步骤

  1. 配置security

  2. 配置授权服务器

  3. 配置资源服务器

2.1 pom.xml添加maven依赖


 
        org.springframework.boot
        spring-boot-starter-parent
        2.2.0.RELEASE
         
 

 
 
        1.8
        Greenwich.SR2
    

    
        
            org.springframework.boot
            spring-boot-starter-web
        

        
            org.springframework.boot
            spring-boot-starter-test
            test
        

        
            org.springframework.cloud
            spring-cloud-starter-security
        

        
            org.springframework.cloud
            spring-cloud-starter-oauth2
        
    

    
        
            
                org.springframework.cloud
                spring-cloud-dependencies
                ${spring-cloud.version}
                pom
                import
            
        
    

2.2 配置Security

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Bean
    public PasswordEncoder passwordEncoder(){
        return new BCryptPasswordEncoder();
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf().disable()
                .authorizeRequests()
                .antMatchers("/oauth/**","/login/**","logout/**")
                .permitAll()
                .anyRequest().authenticated()
                .and()
                .formLogin().permitAll();
    }
}

2.3 配置授权服务器

@Configuration
@EnableAuthorizationServer
public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
        clients.inMemory()
                .withClient("admin")
                .secret(passwordEncoder.encode("123"))
                // 配置访问有效期
                //.accessTokenValiditySeconds(3600)
                // 配置成功后跳转地址
                .redirectUris("http://www.baidu.com")
                // 配置授权范围
                .scopes("all")
                // 配置grant_type模式为授权码模式
                .authorizedGrantTypes("authorization_code");
    }
}

2.4 配置资源服务器

@Configuration
@EnableResourceServer
public class ResourceServerConfig extends ResourceServerConfigurerAdapter {
    @Override
    public void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                .anyRequest().authenticated()
                .and()
                .requestMatchers().antMatchers("/user/**");

    }
}

2.5

实现UserDetailsService,授权账户

@Service
public class UserService implements UserDetailsService {

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        //设置用户密码
        String password = passwordEncoder.encode("123456");
        //创建用户以及权限
        return new User("admin",password, AuthorityUtils.commaSeparatedStringToAuthorityList("admin"));
    }
}

3. 开始测试

3.1 浏览器访问(参数对应授权服务器中的配置

? http://localhost:8080/oauth/authorize?response_type=code&client_id=admin&redirect_url=http://www.baidu.com&scope=all

3.2 选择同意授权

3.3 授权成功后自动跳转至配置好的跳转地址,获取授权码

3.4 postman中请求获取token,账户和密码为授权服务器中配置的账户密码

3.5 填写基本信息后,获取token认证信息