Spring Security Oauth2.0认证授权

29.OAuth2.0-Spring Cloud Securit

2020-04-02  本文已影响0人  LANSHENGYANG

授权服务器配置

EnableAuthorizationServer

@Configuration
@EnableAuthorizationServer
public class AuthorizationServer extends AuthorizationServerConfigurerAdapter {
    //略
}
public class AuthorizationServerConfigurerAdapter implements AuthorizationServerConfigurer {
    public AuthorizationServerConfigurerAdapter() {
    }

    public void configure(AuthorizationServerSecurityConfigurer security) throws Exception {
    }

    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
    }

    public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
    }
}

配置客户端详情信息

 @Override
public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
    //暂时使用内存方式
    clients.inMemory()//使用in-memory存储
            .withClient("c1")//client_id
            .secret(new BCryptPasswordEncoder().encode("secret"))//客户端密钥
            .resourceIds("res1")//资源列表
            .authorizedGrantTypes("authorization_code","password","client_credentials","implicit","refresh_token")//该client允许的授权的类型
            .scopes("all")//允许范围
            .autoApprove(false)//false跳转到授权页面
            .redirectUris("http://www.baidu.com");//加上验证回调地址
}

管理令牌

1.定义TokenConfig
@Configuration
public class TokenConfig {

    @Bean
    public TokenStore tokenStore(){
        return new InMemoryTokenStore();
    }
}
2.定义AuthorizationServerTokenServices
@Autowired
private TokenStore tokenStore;

@Autowired
private ClientDetailsService clientDetailsService;

@Bean
public AuthorizationServerTokenServices tokenServices(){
    DefaultTokenServices service=new DefaultTokenServices();
    service.setClientDetailsService(clientDetailsService);//客户端信信息的服务
    service.setSupportRefreshToken(true);//是否产生刷新令牌
    service.setTokenStore(tokenStore);//令牌存储策略
    service.setAccessTokenValiditySeconds(7200);//令牌默认有效期2小时
    service.setRefreshTokenValiditySeconds(259200);//刷新令牌默认有效期3天
    return service;
}

令牌访问端点配置

配置授权类型(Rant Types)
配置授权端点的URL(Endpoint URLs):
/**
 * 令牌管理服务
 * @return
 */
@Bean
public AuthorizationServerTokenServices tokenServices(){
    DefaultTokenServices service=new DefaultTokenServices();
    service.setClientDetailsService(clientDetailsService);//客户端信信息的服务
    service.setSupportRefreshToken(true);//是否产生刷新令牌
    service.setTokenStore(tokenStore);//令牌存储策略
    service.setAccessTokenValiditySeconds(7200);//令牌默认有效期2小时
    service.setRefreshTokenValiditySeconds(259200);//刷新令牌默认有效期3天
    return service;
}

令牌端点的安全约束

/**
 * 令牌访问端点安全策略
 * @param security
 * @throws Exception
 */
@Override
public void configure(AuthorizationServerSecurityConfigurer security) throws Exception {
    security
            .tokenKeyAccess("permitAll()")//oauth/token_key公开
            .checkTokenAccess("permitAll()")///oauth/check_token公开
            .allowFormAuthenticationForClients();//表单认证,申请令牌
}

web安全配置

上一篇下一篇

猜你喜欢

热点阅读