Spring Authorization Server自定义登录与授权页面

  • 基于该篇文章修改。
  • 目前官方文档并不完善,便做此记录。
  • 置方式来源于官方仓库issues

oauth2-server模块pom添加thymeleaf依赖

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>

登录页面

修改DefaultSecurityConfig

    @Bean
    SecurityFilterChain defaultSecurityFilterChain(HttpSecurity http) throws Exception {
        http.formLogin(form ->
                        form.loginPage("/login")
                                .loginProcessingUrl("/login")
                )
                .authorizeRequests(requests ->
                        requests.antMatchers("/login").permitAll()
                                .anyRequest().authenticated()
                );

        return http.build();
    }

模板页面

<!DOCTYPE html>
<html lang="zh" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>登录页面</title>
</head>
<body>
<h3>登录</h3>
<form th:action="@{/login}" method="post">
    <table>
        <tr>
            <td>用户名:</td>
            <td><input type="text" name="username"></td>
        </tr>
        <tr>
            <td>密码:</td>
            <td><input type="password" name="password"></td>
        </tr>
        <tr>
            <td colspan="2">
                <button type="submit">登录</button>
            </td>
        </tr>
    </table>
</form>
</body>
</html>

添加控制器

@Slf4j
@Controller
public class Oauth2Controller {
    @GetMapping("login")
    public String login() {
        return "login";
    }
}

效果

在这里插入图片描述

授权页面

修改AuthorizationServerConfiguration

void defaultOAuth2AuthorizationServerConfigurer(HttpSecurity http) throws Exception {
        OAuth2AuthorizationServerConfigurer<HttpSecurity> authorizationServerConfigurer = new OAuth2AuthorizationServerConfigurer<>();
        RequestMatcher authorizationServerEndpointsMatcher = authorizationServerConfigurer.getEndpointsMatcher();

		//添加自定义授权页面
        authorizationServerConfigurer.authorizationEndpoint(endpoint -> {
            endpoint.consentPage("/oauth2/consent");
        });
        
        // 拦截 授权服务器相关的请求端点
        http.requestMatcher(authorizationServerEndpointsMatcher)
                .authorizeRequests().anyRequest().authenticated().and()
                // 忽略掉相关端点的csrf
                .csrf(csrf -> csrf.ignoringRequestMatchers(authorizationServerEndpointsMatcher))
                // 应用 授权服务器的配置
                .apply(authorizationServerConfigurer);
    }

添加控制器

@Slf4j
@Controller
public class Oauth2Controller {
    @GetMapping("login")
    public String login() {
        return "login";
    }

    @RequestMapping("/oauth2/consent")
    public String consent(@RequestParam String scope, @RequestParam String client_id, @RequestParam String state, Authentication authentication, Model model) {
        log.info("/oauth2/consent------>scope:{} client_id:{} state:{} authentication:{}",scope,client_id,state,authentication);

        model.addAttribute("scopes", scope.split(" "));
        model.addAttribute("clientId", client_id);
        model.addAttribute("state", state);
        return "consent";
    }
}

模板页面

<!DOCTYPE html>
<html lang="zh" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<form method="post" th:action="@{/oauth2/authorize}">
    <input type="hidden" name="client_id" th:value="${clientId}"/>
    <input type="hidden" name="state" th:value="${state}"/>
    <div th:each="scope : ${scopes}">
        <input type="checkbox" name="scope" th:value="${scope}" th:id="${scope}" th:text="${scope}"/><br/>
    </div>

    <button type="submit">同意</button>
</form>
</body>
</html>

目录结构

在这里插入图片描述

  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 5
    评论
Spring Authorization Server允许我们自定义登录方式。下面是一个示例: 首先,我们需要创建一个自定义的认证提供者(AuthenticationProvider),用于处理自定义登录方式。在这个认证提供者中,我们可以实现自己的认证逻辑。 ```java public class CustomAuthenticationProvider implements AuthenticationProvider { @Override public Authentication authenticate(Authentication authentication) throws AuthenticationException { // 自定义认证逻辑 // ... return new UsernamePasswordAuthenticationToken(username, password, authorities); } @Override public boolean supports(Class<?> authentication) { return authentication.equals(UsernamePasswordAuthenticationToken.class); } } ``` 然后,我们需要将自定义的认证提供者添加到Spring Security的配置中。 ```java @Configuration @EnableWebSecurity public class SecurityConfig extends WebSecurityConfigurerAdapter { @Autowired private CustomAuthenticationProvider customAuthenticationProvider; @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { auth.authenticationProvider(customAuthenticationProvider); } // 其他配置... } ``` 最后,我们可以在Spring Authorization Server的配置中使用自定义的认证方式。 ```java @Configuration public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter { @Autowired private AuthenticationManager authenticationManager; @Override public void configure(ClientDetailsServiceConfigurer clients) throws Exception { clients.inMemory() .withClient("client") .secret("secret") .authorizedGrantTypes("custom_grant_type") .scopes("read", "write") .accessTokenValiditySeconds(3600); } @Override public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception { endpoints.authenticationManager(authenticationManager); } // 其他配置... } ``` 在上面的示例中,我们通过在`configure(ClientDetailsServiceConfigurer clients)`方法中指定`authorizedGrantTypes("custom_grant_type")`来定义了一个自定义授权方式。然后,在`configure(AuthorizationServerEndpointsConfigurer endpoints)`方法中,我们将`authenticationManager`设置为`AuthorizationServerEndpointsConfigurer`的属性,以便使用自定义的认证方式。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值