OAuth2.0授权码模式入门Demo

本文详细介绍了如何使用Spring Cloud OAuth2构建授权服务器和资源服务器。通过配置Spring Security,设置客户端详情,实现authorization_code和implicit授权模式。并提供了登录、获取授权码、令牌及访问指定接口的步骤。
摘要由CSDN通过智能技术生成

代码地址

代码是图灵学院的,我自己学完了之后把代码整理了一下,删掉了无用的代码,然后精简了一下

https://gitee.com/zjj19941/ZJJ_Neaten5.10/tree/master/ZJJ_SpringCloud_Oauth2/demo01

代码

依赖

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

或者 引入spring cloud oauth2依赖

<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-oauth2</artifactId>
</dependency>
 
<!-- spring cloud -->
<dependencyManagement>
    <dependencies>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-dependencies</artifactId>
            <version>Hoxton.SR8</version>
            <type>pom</type>
            <scope>import</scope>
        </dependency>
    </dependencies>
</dependencyManagement>

配置 spring security

@Configuration
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
 
    @Bean
    public PasswordEncoder passwordEncoder(){
        return new BCryptPasswordEncoder();
    }
 
 
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.formLogin().permitAll()
                .and().authorizeRequests()
                .antMatchers("/oauth/**").permitAll()
                .anyRequest().authenticated()
                .and().logout().permitAll()
                .and().csrf().disable();
    }
}
 
@Service
public class UserService implements UserDetailsService {
 
    @Autowired
    private PasswordEncoder passwordEncoder;
 
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        String password = passwordEncoder.encode("123456");
        return new User("fox",password, AuthorityUtils.commaSeparatedStringToAuthorityList("admin"));
    }
}
 
@RestController
@RequestMapping("/user")
public class UserController {
 
    @RequestMapping("/getCurrentUser")
    public Object getCurrentUser(Authentication authentication) {
        return authentication.getPrincipal();
    }
}

配置授权服务器

@Configuration
@EnableAuthorizationServer
public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {
 
    @Autowired
    private PasswordEncoder passwordEncoder;
 
    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
        clients.inMemory()
                //配置client_id
                .withClient("client")
                //配置client-secret
                .secret(passwordEncoder.encode("123123"))
                //配置访问token的有效期
                .accessTokenValiditySeconds(3600)
                //配置刷新token的有效期
                .refreshTokenValiditySeconds(864000)
                //配置redirect_uri,用于授权成功后跳转
                .redirectUris("http://www.baidu.com")
                //配置申请的权限范围
                .scopes("all")
                //配置grant_type,表示授权类型
                .authorizedGrantTypes("authorization_code");
    }
}

配置资源服务器

@Configuration
@EnableResourceServer
public class ResourceServiceConfig extends ResourceServerConfigurerAdapter {
 
    @Override
    public void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
        .anyRequest().authenticated()
        .and().requestMatchers().antMatchers("/user/**");
 
    }
}

测试

authorization_code模式

开始登录

http://localhost:8080/oauth/authorize?response_type=code&client_id=client 或者 http://localhost:8080/oauth/authorize?response_type=code&client_id=client&redirect_uri=http://www.baidu.com&scope=all

image.png
账号 fox 密码 123456

这个账号密码是在下面的类写死的,实际情况是从关系型数据库里面查询出来
image.png

登录成功之后获取授权码

登录之后会自动重定向到百度页面, code=w6FkKd 就是授权码

image.png

为什么会重定向到百度呢?

因为在 授权服务器类上配置了redirectUris属性是百度

image.png

获取token令牌

根据授权码通过post请求获取

访问post请求: http://localhost:8080/oauth/token

image.png
body里面参数:
grant_type:authorization_code
code:w6FkKd
redirect_url:http://www.baidu.com

image.png

账号密码是 client 123123 ,这个是在代码里面下面的地方配置的

image.png
withClient的值是账号
secret的值是密码
redirectUris的值是跳转的url
authorizedGrantTypes就是grant_type

调用成功之后postman返回:
image.png

{
“access_token”: “f7c24754-85f2-4976-9617-a6de9940aec3”,
“token_type”: “bearer”,
“expires_in”: 576,
“scope”: “all”
}

访问指定接口

访问方式1:请求头携带token

image.png

Authorization:bearer f7c24754-85f2-4976-9617-a6de9940aec3

访问方式2:浏览器get请求后面拼接参数

或者浏览器访问:

http://localhost:8080/user/getCurrentUser?access_token=f7c24754-85f2-4976-9617-a6de9940aec3

image.png

implicit简化模式

登录

访问: http://localhost:8080/oauth/authorize?client_id=client&response_type=token&scope=all&redirect_uri=http://www.baidu.com

会直接重定向到下面页面上,输入账号密码 : 账号 fox 密码 123456
image.png

获取access_token

登录成功之后会跳到这个页面
image.png

点击Authorize按钮,点击完成之后会重定向到设置的百度页面,然后url会自动带access_token

https://www.baidu.com/#access_token=5370d3af-78c8-4c90-8e65-617ca4714d7c&token_type=bearer&expires_in=3599
image.png

访问指定的接口

http://localhost:8080/user/getCurrentUser

请求头携带:

Authorization:bearer 5370d3af-78c8-4c90-8e65-617ca4714d7c
image.png

发现能正常访问

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值