最近再学习spring security oauth2。下载了官方的例子sparklr2和tonr2进行学习。但是例子里包含的东西太多,不知道最简单最主要的配置有哪些。所以决定自己尝试搭建简单版本的例子。学习的过程中搭建了认证和资源在一个工程的例子,将token存储在数据库的例子等等 。最后做了这个认证和资源分离的jwt tokens版本。网上找了一些可用的代码然后做了一个整理, 同时测试了哪些代码是必须的。可能仍有一些不必要的代码在,欢迎大家赐教。

一.创建三个spring boot 工程,分别添加必要的依赖。认证和资源的工程需要添加依赖        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-jwt</artifactId>
            <version>1.0.7.RELEASE</version>
        </dependency>

二资源端工程的资源配置文件:

@Configuration
@EnableResourceServer
public class OAuth2ResourceService extends ResourceServerConfigurerAdapter {
    private static final String SPARKLR_RESOURCE_ID = "apple";

@Override
    public void configure(ResourceServerSecurityConfigurer resources) {
        resources.tokenServices(tokenServices()).resourceId(SPARKLR_RESOURCE_ID);
    }
    @Bean
    public TokenStore tokenStore() {
        return new JwtTokenStore(accessTokenConverter());
    }
    @Bean
    public JwtAccessTokenConverter accessTokenConverter() {
        JwtAccessTokenConverter converter = new JwtAccessTokenConverter();
        converter.setSigningKey("123");
        return converter;
    }
    @Bean
    @Primary
    public DefaultTokenServices tokenServices() {
        DefaultTokenServices defaultTokenServices = new DefaultTokenServices();
        defaultTokenServices.setTokenStore(tokenStore());
        return defaultTokenServices;
    }

@Override
    public void configure(HttpSecurity http) throws Exception {
        // @formatter:off
            http
                .authorizeRequests()
                .antMatchers("/hello").access("#oauth2.hasScope('read') or (!#oauth2.isOAuth() and hasRole('ROLE_USER'))");  
        // @formatter:on
    }
}

安全配置文件:

@Configuration
@EnableGlobalMethodSecurity(prePostEnabled = true)
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

@Override
    protected void configure(HttpSecurity http) throws Exception {
         http
            .authorizeRequests()
                .antMatchers("/hello").hasRole("USER")
                .and().csrf().disable()
                .formLogin().loginPage("/login").failureUrl("/login-error");
    }
    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
        auth
            .inMemoryAuthentication()
                .withUser("hello").password("123").roles("USER");
    }
}

三 认证端工程的认证配置文件:

@Configuration
@EnableAuthorizationServer
public class OAuth2AuthorizationServer extends AuthorizationServerConfigurerAdapter {
    private static final String SPARKLR_RESOURCE_ID = "apple";
    
    int accessTokenValiditySeconds = 3600;

@Autowired
    @Qualifier("authenticationManagerBean")
    private AuthenticationManager authenticationManager;
    
       @Bean
        public JwtAccessTokenConverter accessTokenConverter() {
            JwtAccessTokenConverter converter = new JwtAccessTokenConverter();
            converter.setSigningKey("123");
            return converter;
        }

@Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {

// @formatter:off
        clients.inMemory().withClient("tonr")
                     .resourceIds(SPARKLR_RESOURCE_ID)
                     .authorizedGrantTypes("authorization_code", "implicit")
                     .authorities("ROLE_CLIENT")
                     .scopes("read", "write")
                     .secret("secret")
                     .accessTokenValiditySeconds(accessTokenValiditySeconds);
        // @formatter:on
    }
    //jdbc
//    @Bean
//    public DataSource jdbcTokenDataSource(){
//        DriverManagerDataSource dataSource = new DriverManagerDataSource();
//        dataSource.setDriverClassName("com.MySQL.jdbc.Driver");
//        dataSource.setUrl("jdbc:mysql://localhost/test");
//        dataSource.setUsername("root");
//        dataSource.setPassword("root");
//        return dataSource;
//    }
    
    @Bean
    public TokenStore tokenStore() {
//        return new InMemoryTokenStore();
//        return new JdbcTokenStore(jdbcTokenDataSource());
         return new JwtTokenStore(accessTokenConverter());
    }

@Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
        endpoints.tokenStore(tokenStore())
        .authenticationManager(this.authenticationManager)
        .accessTokenConverter(accessTokenConverter());
    }
       @Bean
        @Primary
        public DefaultTokenServices tokenServices() {
            DefaultTokenServices defaultTokenServices = new DefaultTokenServices();
            defaultTokenServices.setTokenStore(tokenStore());
            defaultTokenServices.setSupportRefreshToken(true);
            return defaultTokenServices;
        }
}\

spring security安全配置文件:

@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

@Override
    protected void configure(HttpSecurity http) throws Exception {
         http
            .authorizeRequests()
            .antMatchers("/css/**", "/index").permitAll()
            .and()
            .csrf()
                .requireCsrfProtectionMatcher(new AntPathRequestMatcher("/oauth/authorize"))
                .disable()
                .formLogin().loginPage("/login").failureUrl("/login-error");
    }
    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
        auth
            .inMemoryAuthentication()
                .withUser("hello").password("123").roles("USER");
    }
    @Override
    @Bean
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }
}

四 客户端工程的配置文件:

@Configuration
@EnableOAuth2Client
public class ResourceConfiguration {

@Bean
    public OAuth2ProtectedResourceDetails hello() {
        AuthorizationCodeResourceDetails details = new AuthorizationCodeResourceDetails();
        details.setId("hello");
        details.setClientId("tonr");
        details.setClientSecret("secret");
        details.setAccessTokenUri("http://localhost:8083/auth/oauth/token");//认证服务器地址+/oauth/token
        details.setUserAuthorizationUri("http://localhost:8083/auth/oauth/authorize");//认证服务器地址+/oauth/authorize
        details.setScope(Arrays.asList("read", "write"));
        return details;
    }

@Bean
    public OAuth2RestTemplate helloRestTemplate(OAuth2ClientContext oauth2Context) {//客户端的信息被封装到OAuth2RestTemplate用于请求资源
        return new OAuth2RestTemplate(hello(), oauth2Context);
    }
}

在业务逻辑的serviceImp类中 注入helloRestTemplate 然后:

@Autowired
    private RestOperations helloRestTemplate

public String getDataFromResoureServer() {;

String data= helloRestTemplate.getForObject(URI.create("http://localhost:8080/resource/hello"), String.class);//请求资源服务器资源的路径

return data;

}

spring security安全配置文件:

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .authorizeRequests()
                .antMatchers("/css/**", "/index").permitAll()      
                .and()
            .formLogin()
                .loginPage("/login").failureUrl("/login-error");    
    }

@Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
        auth
            .inMemoryAuthentication()
                .withUser("insecure").password("123").roles("USER");
    }
}

http://blog.csdn.net/u010139801/article/details/68484090

spring security oauth2 jwt 认证和资源分离的配置文件(java类配置版)的更多相关文章

  1. Spring Security OAuth2.0认证授权六:前后端分离下的登录授权

    历史文章 Spring Security OAuth2.0认证授权一:框架搭建和认证测试 Spring Security OAuth2.0认证授权二:搭建资源服务 Spring Security OA ...

  2. 【Spring Cloud & Alibaba 实战 | 总结篇】Spring Cloud Gateway + Spring Security OAuth2 + JWT 实现微服务统一认证授权和鉴权

    一. 前言 hi,大家好~ 好久没更文了,期间主要致力于项目的功能升级和问题修复中,经过一年时间的打磨,[有来]终于迎来v2.0版本,相较于v1.x版本主要完善了OAuth2认证授权.鉴权的逻辑,结合 ...

  3. Spring Security OAuth2.0认证授权二:搭建资源服务

    在上一篇文章[Spring Security OAuth2.0认证授权一:框架搭建和认证测试](https://www.cnblogs.com/kuangdaoyizhimei/p/14250374. ...

  4. Spring Security OAuth2.0认证授权三:使用JWT令牌

    Spring Security OAuth2.0系列文章: Spring Security OAuth2.0认证授权一:框架搭建和认证测试 Spring Security OAuth2.0认证授权二: ...

  5. Spring Security OAuth2.0认证授权五:用户信息扩展到jwt

    历史文章 Spring Security OAuth2.0认证授权一:框架搭建和认证测试 Spring Security OAuth2.0认证授权二:搭建资源服务 Spring Security OA ...

  6. Spring Security OAuth2.0认证授权四:分布式系统认证授权

    Spring Security OAuth2.0认证授权系列文章 Spring Security OAuth2.0认证授权一:框架搭建和认证测试 Spring Security OAuth2.0认证授 ...

  7. Spring Security + OAuth2 + JWT 基本使用

    Spring Security + OAuth2 + JWT 基本使用 前面学习了 Spring Security 入门,现在搭配 oauth2 + JWT 进行测试. 1.什么是 OAuth2 OA ...

  8. Springboot集成Spring Security实现JWT认证

    我最新最全的文章都在南瓜慢说 www.pkslow.com,欢迎大家来喝茶! 1 简介 Spring Security作为成熟且强大的安全框架,得到许多大厂的青睐.而作为前后端分离的SSO方案,JWT ...

  9. Springboot WebFlux集成Spring Security实现JWT认证

    我最新最全的文章都在南瓜慢说 www.pkslow.com,欢迎大家来喝茶! 1 简介 在之前的文章<Springboot集成Spring Security实现JWT认证>讲解了如何在传统 ...

随机推荐

  1. C语言之数值计算--级数算法

    在编程语言的学习中,我们学习过不少的算法,比如累加,累乘,数值交换,排序等等.在一些软件比赛和面试题中,有一类算法不容忽视,属于高频题目,我之前去企业面试的时候就遇到这样的一类题目,题目不算难,掌握方 ...

  2. 第十八篇 ANDROID的声音管理系统及服务

     声音管理系统用来实现声音的输入和输出.声音的控制和路由等功能,包括主和各种音源的音量调节.声音焦点控制,声音外设的检测和状态管理,声音源输入和输出的策略管理.音效的播放.音轨设置和播放.录音设置 ...

  3. Leetcode_278_First Bad Version

    本文是在学习中的总结,欢迎转载但请注明出处:http://blog.csdn.net/pistolove/article/details/49719255 You are a product mana ...

  4. ruby正则表带式对象使用备忘

    ruby对于正则表达式的使用是非常灵活的,提供了专门的正则表达式对象Regexp.其包括match实例方法,字符串也含有该方法.so可以这么做: /a/ =~ "a" " ...

  5. Windows平台安装及配置Hadoop(不借助cygwin)

    由于项目需要,我在VMware上装了几个虚拟机Windows server 2012 R2,并要搭建Hadoop集群.刚刚入门hadoop,一头雾水,然后开始搜各种教程,首先是选用cygwin进行安装 ...

  6. Spring Cloud入门教程-Hystrix断路器实现容错和降级

    简介 Spring cloud提供了Hystrix容错库用以在服务不可用时,对配置了断路器的方法实行降级策略,临时调用备用方法.这篇文章将创建一个产品微服务,注册到eureka服务注册中心,然后我们使 ...

  7. Python list 两个不等长列表交叉合并

    遇到一个需求,需要对两个长度不一定相等的列表进行交叉合并.像拉拉链一样(两边的拉链不一定相等). 如: a = [1, 3, 5] b = [2, 4, 6, 8] 需将a, b 合并为 c c = ...

  8. c#调用野狗云 rest api

    野狗云就不多介绍了,这里主要是记录一下c#调用他们提供的rest api,把数据post到野狗云存储,直接上代码 static void Main(string[] args) { string st ...

  9. ScrollView的顶部下拉和底部上拉回弹效果

    要实现ScrollView的回弹效果,需要对其进行触摸事件处理.先来看一下简单的效果: 根据Android的View事件分发处理机制,下面对dispatchTouchEvent进行详细分析: 在加载布 ...

  10. jquery中利用队列依次执行动画

    如果有5个隐藏的div,要让它们依次显示,通常的做法是要一个一个嵌套在回调函数里面,这样导致代码看起来非常不直观. $("#div1").slideDown(1000,functi ...