SpringSecurity-OAuth2

1、创建项目

创建项目

2、添加依赖

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.6.6</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.xdd</groupId>
    <artifactId>OAuth2</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>OAuth2</name>
    <description>Demo project for Spring Boot</description>
    <properties>
        <java.version>1.8</java.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-oauth2</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-security</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>
    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-dependencies</artifactId>
                <version>Greenwich.SR2</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>
    
    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
</project>

3、授权码模式

(1)、创建配置(SecurityConfig、AuthorizationServerConfig、ResourceServerConfig)

SecurityConfig.java
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Bean
    public PasswordEncoder getPassword(){
        return new BCryptPasswordEncoder();
    }
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        //授权认证
        http.authorizeRequests()
                //白名单页面不需要认证
                .antMatchers("oauth/**").permitAll()
                //拦截请求进行认证
                .anyRequest().authenticated()
                .and()
                .formLogin().permitAll()
                .and()
                .csrf().disable();
    }
}
AuthorizationServerConfig.java
//授权服务器配置
@Configuration
@EnableAuthorizationServer
public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {
    @Autowired
    private PasswordEncoder passwordEncoder;
    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
        clients.inMemory()
                //配置clientid
                .withClient("admin")
                //配置client-recret
                .secret(passwordEncoder.encode("521314"))
                //token有效期
                .accessTokenValiditySeconds(600)
                //授权成功跳转地址
                .redirectUris("http://www.baidu.com")
                //配置申请的权限范围
                .scopes("all")
                //配置授权类型
                .authorizedGrantTypes("authorization_code");
    }
}
ResourceServerConfig.java
//资源服务器配置
@Configuration
@EnableResourceServer
public class ResourceServerConfig extends ResourceServerConfigurerAdapter {
    @Override
    public void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                //拦截请求进行认证
                .anyRequest().authenticated()
                .and()
                //白名单
                .requestMatchers().antMatchers("/user/**");
    }
}

(2)、创建User、UserService、UserController

User.java
public class User implements UserDetails {
    private String username;//用户名
    private String password;//密码
    private List<GrantedAuthority> authorities;//权限列表
    public User(String username, String password, List<GrantedAuthority> authorities) {
        this.username = username;
        this.password = password;
        this.authorities = authorities;
    }
    @Override//是否未过期
    public boolean isAccountNonExpired() {
        return true;
    }
    @Override//是否未锁定
    public boolean isAccountNonLocked() {
        return true;
    }
    @Override//证书是否未过期
    public boolean isCredentialsNonExpired() {
        return true;
    }
    @Override//用户是否启用
    public boolean isEnabled() {
        return true;
    }
	//Getter、Setter方法略
}
UserService.java
@Service
public class UserService implements UserDetailsService {
    @Autowired
    private PasswordEncoder passwordEncoder;
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //校验密码
        String password=passwordEncoder.encode("521314");
        return new User(username,password, AuthorityUtils.commaSeparatedStringToAuthorityList("admin,normal,ROLE_leader"));
    }
}
UserController.java
@RestController
@RequestMapping("/user")
public class UserController {
    @GetMapping("currentUser")
    public Object getCurrentUser(Authentication authentication){
        return authentication.getPrincipal();
    }
}

(3)、启动项目

  1. 访问地址:http://localhost:8080/oauth/authorize?response_type=code&client_id=admin&scope=all&redirect_uri=http://www.baidu.com
  2. 输入账户名密码登录
    在这里插入图片描述
  3. 登录成功
    !](https://img-blog.csdnimg.cn/47233e13e1e94d5eb6ae0f01f666f196.png)
    跳转成功后获取地址栏参数:code
    在这里插入图片描述
  4. 使用postman获取token
    在这里插入图片描述
  5. 调用接口获取用户信息
    在这里插入图片描述

4、密码模式(与授权码模式类似)

(1)、配置SecurityConfig、AuthorizationServerConfig

SecurityConfig.java
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Bean
    public PasswordEncoder getPassword(){
        return new BCryptPasswordEncoder();
    }
    @Bean
    @Override
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        //授权认证
        http.authorizeRequests()
                //白名单页面不需要认证
                .antMatchers("oauth/**").permitAll()
                //拦截请求进行认证
                .anyRequest().authenticated()
                .and()
                .formLogin().permitAll()
                .and()
                .csrf().disable();
    }
}
AuthorizationServerConfig.java
@Configuration
@EnableAuthorizationServer
public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {
    @Autowired
    private PasswordEncoder passwordEncoder;
    @Autowired
    private AuthenticationManager authenticationManager;
    @Autowired
    private UserService userService;
    //密码模式
    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
        endpoints.authenticationManager(authenticationManager)
                 .userDetailsService(userService);
    }
    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
        clients.inMemory()
                //配置clientid
                .withClient("admin")
                //配置client-recret
                .secret(passwordEncoder.encode("521314"))
                //token有效期
                .accessTokenValiditySeconds(600)
                //授权成功跳转地址
                .redirectUris("http://www.baidu.com")
                //配置申请的权限范围
                .scopes("all")
                //配置授权类型authorization_code:授权码模式,password:密码模式
                .authorizedGrantTypes("password");
    }
}

(2)、启动项目

在这里插入图片描述

(3)、将token存入redis

1、添加redis依赖

pom.xml

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-pool2</artifactId>
</dependency>
2、配置redis的host

application.yml

spring:
  redis:
    host: 124.221.XXX.XXX
3、创建redis配置

RedisConfig.java

@Configuration
public class RedisConfig {
    @Autowired
    private RedisConnectionFactory redisConnectionFactory;
    @Bean
    public TokenStore redisTokenStore(){
        return new RedisTokenStore(redisConnectionFactory);
    }
}
4、更改AuthorizationServerConfig

AuthorizationServerConfig.java

@Configuration
@EnableAuthorizationServer
public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {
    @Autowired
    private PasswordEncoder passwordEncoder;
    @Autowired
    private AuthenticationManager authenticationManager;
    @Autowired
    private UserService userService;
    @Autowired
    private TokenStore tokenStore;
    //密码模式
    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
        endpoints.authenticationManager(authenticationManager)
                 .userDetailsService(userService)
                .tokenStore(tokenStore);
    }
    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
        clients.inMemory()
                //配置clientid
                .withClient("admin")
                //配置client-recret
                .secret(passwordEncoder.encode("521314"))
                //token有效期
                .accessTokenValiditySeconds(600)
                //授权成功跳转地址
                .redirectUris("http://www.baidu.com")
                //配置申请的权限范围
                .scopes("all")
                //配置授权类型authorization_code:授权码模式,password:密码模式
                .authorizedGrantTypes("password");
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值