Spring Boot 配置OAuth2

本文详细介绍了如何使用Spring Security OAuth2配置授权服务和资源服务,包括必要的依赖、客户端细节配置、安全约束设置等关键步骤。

需要的包

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

配置授权服务

package com.uwo.oss.security.oauth2.configuration;
import com.uwo.oss.security.configuration.OssUserDetailsService;
import com.uwo.oss.token.configuration.OssJwtAccessTokenConverter;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
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.error.OAuth2AccessDeniedHandler;
import org.springframework.security.oauth2.provider.error.OAuth2AuthenticationEntryPoint;
import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter;
import org.springframework.security.oauth2.provider.token.store.JwtTokenStore;

/**
 * 授权服务
 * Created by yanhao on 2017/5/26.
 */
@Configuration
@EnableAuthorizationServer
public class OssAuthorizationConfiguration extends AuthorizationServerConfigurerAdapter {

    private static final Logger log = Logger.getLogger(OssAuthorizationConfiguration.class);

    @Autowired
    private OssUserDetailsService userDetailsService;

    @Autowired
    private OssJwtAccessTokenConverter jwtAccessTokenConverter;

    @Autowired
    private AuthenticationManager authenticationManager;

    @Autowired
    private OssClientDetailsService clientDetailsService;
    @Autowired
    private OssAuthorizationServerTokenServices authorizationServerTokenServices;

    /**
     * 用来定义授权与管理token
     * @param endpoints
     * @throws Exception
     */
    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
        log.warn("configure AuthorizationServerEndpointsConfigurer");
        log.warn("tokenServices " + authorizationServerTokenServices);
        jwtAccessTokenConverter.setSigningKey("uwo");
        endpoints
            // 持久操作
            .tokenStore(new JwtTokenStore(jwtTokenEnhancer()))
            .tokenEnhancer(jwtTokenEnhancer())
            .authenticationManager(authenticationManager)
            .userDetailsService(userDetailsService)
        ;
    }

    /**
     * 管理客户端详情
     * @param clients
     * @throws Exception
     */
    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
        log.warn("configure ClientDetailsServiceConfigurer");
        clients.inMemory()
                .withClient("123456")
                .secret("654321") 
                .scopes("openid")
                .autoApprove(true)
                .authorities("READ", "WRITE")
                .authorizedGrantTypes("implicit", "refresh_token", "password", "authorization_code");
    }

    /**
     * 配置token的安全约束
     * @param oauthServer
     * @throws Exception
     */
    @Override
    public void configure(AuthorizationServerSecurityConfigurer oauthServer) throws Exception {
        oauthServer
            .accessDeniedHandler(oauth2AccessDeniedHandler())
            .authenticationEntryPoint(oauth2AuthenticationEntryPoint())
            .allowFormAuthenticationForClients();
        log.warn("configure AuthorizationServerSecurityConfigurer");
    }

    @Bean
    protected JwtAccessTokenConverter jwtTokenEnhancer() {
        OssJwtAccessTokenConverter converter = new OssJwtAccessTokenConverter();
        converter.setSigningKey("uwo");
        return converter;
    }

    @Bean
    public OAuth2AccessDeniedHandler oauth2AccessDeniedHandler() {
        return new OAuth2AccessDeniedHandler();
    }

    @Bean
    public OAuth2AuthenticationEntryPoint oauth2AuthenticationEntryPoint() {
        return new OAuth2AuthenticationEntryPoint();
    } 
} 

配置资源服务

package com.uwo.oss.client.configuration;

import com.uwo.oss.token.configuration.OssJwtAccessTokenConverter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.expression.EvaluationContext;
import org.springframework.expression.ExpressionParser;
import org.springframework.security.access.expression.SecurityExpressionHandler;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.core.Authentication;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;
import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configurers.ResourceServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.token.DefaultTokenServices;
import org.springframework.security.oauth2.provider.token.ResourceServerTokenServices;
import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter;
import org.springframework.security.oauth2.provider.token.store.JwtTokenStore;
import org.springframework.security.web.FilterInvocation;

/**
 * 资源服务
 * Created by yanhao on 2017/5/31.
 */
@Configuration
@EnableResourceServer
public class OssResourceServerConfiguration extends ResourceServerConfigurerAdapter {

    private static final String RESOURCE_ID = "restservice";

    @Override
    public void configure(HttpSecurity http) throws Exception {
        http
            .csrf().disable()
            .authorizeRequests()
            .antMatchers("/user/**").authenticated();
    }

    @Override
    public void configure(ResourceServerSecurityConfigurer resources) throws Exception {
        resources
            .resourceId(RESOURCE_ID)
            .tokenServices(defaultTokenServices());
    }

    @Bean
    public ResourceServerTokenServices defaultTokenServices() {
        final DefaultTokenServices defaultTokenServices = new DefaultTokenServices();
        defaultTokenServices.setTokenEnhancer(jwtTokenEnhancer());
        defaultTokenServices.setTokenStore(new JwtTokenStore(jwtTokenEnhancer()));
        return defaultTokenServices;
    }

    @Bean
    protected JwtAccessTokenConverter jwtTokenEnhancer() {
        OssJwtAccessTokenConverter converter = new OssJwtAccessTokenConverter();
        converter.setSigningKey("uwo");
        return converter;
    }

}

转载于:https://my.oschina.net/yan5845hao/blog/912291

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值