OAuth 2认证模式 - 密码模式(password)


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
    @Bean
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }
    
    @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;
    @Autowired
    private AuthenticationManager authenticationManager;


    /**
     * 使用密码模式所需配置
     * @Author simon
     * @Date  2021/11/16
     * @Param [endpoints]
     * @return void
     **/
    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
        endpoints.authenticationManager(authenticationManager);
    }

    /**
     * 使用授权码模式所需配置
     * @Author simon
     * @Date  2021/11/16
     * @Param [clients]
     * @return void
     **/
    @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("password");
    }
}

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 postman中请求获取token,账户和密码为授权服务器中配置的账户密码

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