SpringCloud系列【security & oauth2】

 

首先推荐看这篇:https://blog.csdn.net/u014730165/article/details/83181754

另外一个博客的源码传送:https://github.com/babylikebird/Micro-Service-Skeleton

环境:

大部分和推荐的这边文章的pom依赖相同,不过用了nacos作为配置中心和注册中心,这里面的版本比较重要,兼容性不用调。

兼容性问题:

 问题1:这个版本可以解决redis兼容问题 【RedisConnection.set([B[B)V-】

参见文章:https://www.cnblogs.com/nicori/p/10001759.html

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

springcloud:Finchley.RELEASE

springboot:2.0.0.RELEASE

JDK:1.8

nacos:0.2.1.RELEASE(暂时不讲)

springcloud版本和springboot版本要注意,

大版本对应:

Spring BootSpring Cloud
1.2.xAngel版本
1.3.xBrixton版本
1.4.x stripesCamden版本
1.5.xDalston版本、Edgware版本
2.0.xFinchley版本

 

代码:

application.yml

spring:
  application:
    name: member
  redis:
    password: 12345678
    database: 0
    port: 6379
    host: 10.105.17.xxx
    timeout: 2000
  datasource:
    url: jdbc:mysql://10.100.248.3:3306/oauth2?useUnicode=true&characterEncoding=utf8
    username: root
    password: root
    druid:
      driver-class-name: com.mysql.jdbc.Driver
server:
  port: 8080
  servlet:
    context-path: /
OAuth2ServerConfig.java

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.annotation.Order;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.password.PasswordEncoder;
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.ClientDetailsService;
import org.springframework.security.oauth2.provider.client.JdbcClientDetailsService;
import org.springframework.security.oauth2.provider.token.DefaultTokenServices;
import org.springframework.security.oauth2.provider.token.store.redis.RedisTokenStore;

import javax.sql.DataSource;

@Order(2)
@Configuration
@EnableAuthorizationServer
public class OAuth2ServerConfig extends AuthorizationServerConfigurerAdapter {

    @Autowired
    private AuthenticationManager authenticationManager;
    @Autowired
    UserDetailsService userDetailsService;
    @Autowired
    RedisTemplate redisTemplate;
    @Autowired
    private DataSource dataSource;
    @Autowired
    PasswordEncoder passwordEncoder;


    @Bean
    RedisTokenStore redisTokenStore() {
        return new RedisTokenStore(redisTemplate.getConnectionFactory());
    }

    @Bean
    public ClientDetailsService clientDetails() {
        return new JdbcClientDetailsService(dataSource);
    }

    @Override
    public void configure(AuthorizationServerSecurityConfigurer oauthServer) throws Exception {
        oauthServer
                .realm("xxxx-service")
                //url:/oauth/token_key,exposes public key for token verification if using JWT tokens
                .tokenKeyAccess("permitAll()")
                //url:/oauth/check_token allow check token
                .checkTokenAccess("isAuthenticated()")
                .allowFormAuthenticationForClients();
    }


    /**
     * jdbc token 配置
     */

    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
        endpoints.authenticationManager(authenticationManager)
                .userDetailsService(userDetailsService)
                .tokenStore(redisTokenStore());
        endpoints.tokenServices(defaultTokenServices());
    }

    @Primary
    @Bean
    public DefaultTokenServices defaultTokenServices() {
        DefaultTokenServices tokenServices = new DefaultTokenServices();
        tokenServices.setTokenStore(redisTokenStore());
        tokenServices.setSupportRefreshToken(true);
        tokenServices.setClientDetailsService(clientDetails());
        // token有效期自定义设置,默认12小时
        tokenServices.setAccessTokenValiditySeconds(60 * 60 * 12);
        //默认30天,这里修改
        tokenServices.setRefreshTokenValiditySeconds(60 * 60 * 24 * 7);
        return tokenServices;
    }

    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
        clients.withClientDetails(clientDetails());
//        clients.inMemory()
//                .withClient("dev")
//                .secret(passwordEncoder.encode("dev"))
//                .redirectUris("http://example.com")
//                .authorizedGrantTypes("authorization_code", "client_credentials", "refresh_token",
//                        "password", "implicit")
//                .scopes("all")
//                .resourceIds("oauth2-resource")
//                .accessTokenValiditySeconds(7200)
//                .refreshTokenValiditySeconds(9200);
    }
}
ResourceServerConfiguration.java

import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;
import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter;

/**
 * OAuth 资源服务器配置
 *
 * @author
 * @date 2018-05-29
 */

@Order(6)
@Configuration
@EnableResourceServer
public class ResourceServerConfiguration extends ResourceServerConfigurerAdapter {
    @Override
    public void configure(HttpSecurity http) throws Exception {
        http.csrf()
                .disable()
                .authorizeRequests()
                .antMatchers("/oauth/**")
                .permitAll()
                .anyRequest()
                .authenticated();
    }
}
WebSecurityConfig.java

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.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;

@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    PasswordEncoder passwordEncoder;

    @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.httpBasic().and().authorizeRequests()
                .antMatchers("/oauth/**","/login")
                .permitAll()
                .anyRequest()
                .authenticated()
                .and().csrf().disable();
    }

    @Bean
    @Override
    protected UserDetailsService userDetailsService(){
        InMemoryUserDetailsManager manager = new InMemoryUserDetailsManager();
        manager.createUser(User.withUsername("hello1").password(passwordEncoder.encode("123456")).authorities("USER").build());
        manager.createUser(User.withUsername("hello2").password(passwordEncoder.encode("123456")).authorities("USER").build());
        return manager;
    }
}

postMan验证:

授权码模式

1、获取授权码:

http://localhost:8080/oauth/authorize?response_type=code&client_id=dev&redirect_uri=http://example.com&scop=all

浏览器中回车,输入WebSecurityConfig类中的userDetailsService方法里添加username和password,后期从数据库读取

回调的地址栏有code

 

postman获取access_token

 

使用token访问自己的接口,Authorization选Oauth2填写刚才的access_token;或者Header里面直接添加bearer+空格+access_token

acess_token刷新

客户端模式(client)

密码模式(password)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值