oauth样例项目【01】之 使用auth-code进行认证授权

源码

https://github.com/gaoxinfu/oauth-sample/tree/main/oauth-sample-01

pom.xml

<?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>1.5.10.RELEASE</version>
        <relativePath /> <!-- lookup parent from repository -->
    </parent>

    <groupId>com.gaoxinfu.oauth.sample</groupId>
    <artifactId>oauth-server</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>sample01-授权服务器</name>
    <description>Demo project for Spring Boot</description>

    <properties>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <!--springboot web 服务器-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
        </dependency>
        <!-- for OAuth 2.0 -->
        <dependency>
            <groupId>org.springframework.security.oauth</groupId>
            <artifactId>spring-security-oauth2</artifactId>
        </dependency>

        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
</project>

在这里插入图片描述

在这里插入图片描述
在这里插入图片描述

授权服务配置

package com.gaoxinfu.oauth.sample.config;

import org.springframework.context.annotation.Configuration;
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;

/**
 * 授权服务器配置
 */
@Configuration
@EnableAuthorizationServer
public class AuthorizationServerConfig extends
        AuthorizationServerConfigurerAdapter {

    @Override
    public void configure(ClientDetailsServiceConfigurer clients)
            throws Exception {
        clients.inMemory()
            //客户端id
            .withClient("clientapp")
             //密码
            .secret("112233")
             //一般是发起的寻求获取auth-code的客户端的一个地址,我们在这里自己写在了TokenController中用于显示返回的code
            .redirectUris("http://localhost:9001/token/api/callback")
            // 授权码模式
            .authorizedGrantTypes("authorization_code")
            //权限范围设置
            .scopes("read_userinfo", "read_contacts");
    }

}

在这里插入图片描述

账户密码的配置

server.port=9001

# Spring Security Setting
security.user.name=gaoxinfu
security.user.password=123456

这里演示开始获取auth-code时候,需要账户密码登录之后,才可以继续下一步
在这里插入图片描述

资源服务配置

package com.gaoxinfu.oauth.sample.config;

import org.springframework.context.annotation.Configuration;
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;

/**
 * 资源服务配置
 */
@Configuration
@EnableResourceServer
public class ResourceServerConfig extends ResourceServerConfigurerAdapter {

    @Override
    public void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
            .anyRequest()
            .authenticated()
        .and()
            .requestMatchers()
            .antMatchers("/api/**");
    }

}

在这里插入图片描述

UserController演示资源的访问

package com.gaoxinfu.oauth.sample.controller;

import com.gaoxinfu.oauth.sample.entity.UserEntity;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.User;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;

@Controller
public class UserController {

    /**
     *
     * @return
     */
    @GetMapping("/api/getUser")
    public ResponseEntity<UserEntity> getUser() {
        User user = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        return ResponseEntity.ok(new UserEntity(user.getUsername(),user.getUsername() + "@aliyun.com"));
    }
}

在这里插入图片描述

演示:

获取授权码:auth-code

这里我们通过浏览器去演示
获取auth-code
http://localhost:9001/oauth/authorize?client_id=clientapp&redirect_uri=http://localhost:9001//token/api/callback&response_type=code&scope=read_userinfo

填写账户名密码
在这里插入图片描述

在这里插入图片描述

授权同意还是拒绝,这里我们选择同意Approve
在这里插入图片描述

通过回调通知的方式给我们了auth-code
在这里插入图片描述
oauth code = bOhDxC

获取token

这里我们通过postman去演示

http://localhost:9001/oauth/token?code=n4xh0t&grant_type=authorization_code&redirect_uri=http://localhost:9001/token/api/callback&scope=read_userinfo

Query Params配置
在这里插入图片描述
在这里插入图片描述

授权类型
在这里插入图片描述

内容类型设置
在这里插入图片描述

发送请求,获取结果
在这里插入图片描述

附:这里注意下,如果一旦因为配置获取参数输入有误,获取失败,需要重新获取auth-code

使用token获取用户资源

在这里插入图片描述

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
以下是一个基于Spring Security OAuth2的认证授权代码示例: 1. 添加Maven依赖 ```xml <dependency> <groupId>org.springframework.security.oauth</groupId> <artifactId>spring-security-oauth2</artifactId> <version>2.4.0.RELEASE</version> </dependency> ``` 2. 配置OAuth2服务器 ```java @Configuration @EnableAuthorizationServer public class OAuth2AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter { @Autowired private AuthenticationManager authenticationManager; @Autowired private DataSource dataSource; @Override public void configure(ClientDetailsServiceConfigurer clients) throws Exception { clients.jdbc(dataSource); } @Override public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception { endpoints.authenticationManager(authenticationManager); } } ``` 3. 配置资源服务器 ```java @Configuration @EnableResourceServer public class OAuth2ResourceServerConfig extends ResourceServerConfigurerAdapter { @Override public void configure(HttpSecurity http) throws Exception { http.authorizeRequests().anyRequest().authenticated(); } } ``` 4. 配置Spring Security ```java @Configuration @EnableWebSecurity public class SecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { http.authorizeRequests().antMatchers("/oauth/**").permitAll().anyRequest().authenticated().and().csrf().disable(); } @Override @Bean public AuthenticationManager authenticationManagerBean() throws Exception { return super.authenticationManagerBean(); } } ``` 5. 配置数据源 ```java @Configuration public class DataSourceConfig { @Bean @ConfigurationProperties(prefix = "spring.datasource") public DataSource dataSource() { return DataSourceBuilder.create().build(); } } ``` 6. 配置应用属性 ```properties spring.datasource.url=jdbc:mysql://localhost:3306/oauth2 spring.datasource.username=root spring.datasource.password=root security.oauth2.client.client-id=client security.oauth2.client.client-secret=secret security.oauth2.client.access-token-validity-seconds=3600 security.oauth2.client.authorized-grant-types=authorization_code,refresh_token,password,client_credentials security.oauth2.client.scope=read,write security.oauth2.resource.id=resource security.user.name=user security.user.password=password security.user.roles=USER ``` 以上代码仅供参考,具体实现需要根据实际场景进行调整。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

东山富哥

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值