Java17 --- SpringSecurity之OAuth2

一、OAuth2

1.1、使用github以授权码方式

1.1.1、注册应用程序

 

 

1.1.2、测试代码

 pom依赖

<dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-oauth2-client</artifactId>
        </dependency>
spring:
  security:
    oauth2:
      client:
        registration:
          github:
            client-id: Ov23liQnQPka0x1qX6ZI
            client-secret: 278f3ad4ecdd8dad4b318d7bd8d33f2bb9428019
@Controller
public class IndexController {
    @GetMapping("/")
    public String index(Model model, @RegisteredOAuth2AuthorizedClient OAuth2AuthorizedClient authorizedClient,
                        @AuthenticationPrincipal OAuth2User oauth2User) {
        model.addAttribute("userName", oauth2User.getName());
        model.addAttribute("clientName", authorizedClient.getClientRegistration().getClientName());
        model.addAttribute("userAttributes", oauth2User.getAttributes());
        return "index";
    }
}
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="https://www.thymeleaf.org" xmlns:sec="https://www.thymeleaf.org/thymeleaf-extras-springsecurity5">
<head>
  <title>Spring Security - OAuth 2.0 Login</title>
  <meta charset="utf-8" />
</head>
<body>
<div style="float: right" th:fragment="logout" sec:authorize="isAuthenticated()">
  <div style="float:left">
    <span style="font-weight:bold">User: </span><span sec:authentication="name"></span>
  </div>
  <div style="float:none">&nbsp;</div>
  <div style="float:right">
    <form action="#" th:action="@{/logout}" method="post">
      <input type="submit" value="Logout" />
    </form>
  </div>
</div>
<h1>OAuth 2.0 Login with Spring Security</h1>
<div>
  You are successfully logged in <span style="font-weight:bold" th:text="${userName}"></span>
  via the OAuth 2.0 Client <span style="font-weight:bold" th:text="${clientName}"></span>
</div>
<div>&nbsp;</div>
<div>
  <span style="font-weight:bold">User Attributes:</span>
  <ul>
    <li th:each="userAttribute : ${userAttributes}">
      <span style="font-weight:bold" th:text="${userAttribute.key}"></span>: <span th:text="${userAttribute.value}"></span>
    </li>
  </ul>
</div>
</body>
</html>

 

 

 

  • 3
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
当然可以!以下是一个简单的Spring Security OAuth2教程: 1. 首先,确保你的项目已经添加了Spring SecurityOAuth2的依赖。 2. 创建一个配置类,用于配置Spring SecurityOAuth2。可以参考以下示例: ```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(); } } ``` 这个配置类启用了Spring Security,并配置了允许访问`/oauth/**`路径的所有请求,其他请求需要进行身份验证。 3. 创建一个OAuth2授权服务器配置类,用于配置OAuth2服务器。可以参考以下示例: ```java @Configuration @EnableAuthorizationServer public class OAuth2Config extends AuthorizationServerConfigurerAdapter { @Autowired private AuthenticationManager authenticationManager; @Override public void configure(AuthorizationServerSecurityConfigurer security) throws Exception { security.checkTokenAccess("isAuthenticated()"); } @Override public void configure(ClientDetailsServiceConfigurer clients) throws Exception { clients.inMemory() .withClient("client_id") .secret("client_secret") .authorizedGrantTypes("authorization_code", "refresh_token") .scopes("read", "write") .redirectUris("http://localhost:8080/callback"); } @Override public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception { endpoints.authenticationManager(authenticationManager); } } ``` 这个配置类启用了授权服务器,并配置了一个内存的客户端,使用授权码和刷新令牌来授予读写权限。可以根据需要进行修改。 4. 创建一个资源服务器配置类,用于配置OAuth2资源服务器。可以参考以下示例: ```java @Configuration @EnableResourceServer public class ResourceServerConfig extends ResourceServerConfigurerAdapter { @Override public void configure(HttpSecurity http) throws Exception { http .authorizeRequests() .antMatchers("/api/**").authenticated() .and() .csrf().disable(); } } ``` 这个配置类启用了资源服务器,并配置了需要进行身份验证的`/api/**`路径。 5. 创建一个控制器类,用于测试保护的API。可以参考以下示例: ```java @RestController @RequestMapping("/api") public class ApiController { @GetMapping("/hello") public String hello() { return "Hello, OAuth2!"; } } ``` 这个控制器类定义了一个简单的API接口,需要进行身份验证才能访问。 以上是一个简单的Spring Security OAuth2教程,希望对你有帮助!如果有任何问题,请随时提问。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

鸭鸭老板

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

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

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

打赏作者

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

抵扣说明:

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

余额充值