具有自定义登录的Spring Authorization Server



我正在尝试新的spring框架

<artifactId>spring-security-oauth2-authorization-server</artifactId>

我从baeldung那里得到了完美的POC,但当我尝试超越默认配置时,我没能让事情正常工作。

我试图配置一个自定义登录页面,用一个自定义路径来张贴用户信息,登录页面显示得很好,但在张贴表单(用户名/密码棒(后,我得到了一个404(NOT_FOUND(

这是我的配置:

@Bean
@Order(Ordered.HIGHEST_PRECEDENCE)
public SecurityFilterChain authServerSecurityFilterChain(HttpSecurity http) throws Exception {
// Authorization server Oauth2 default config commented
//        OAuth2AuthorizationServerConfiguration.applyDefaultSecurity(http);
//Extracted from Oauth2 default config
OAuth2AuthorizationServerConfigurer<HttpSecurity> authorizationServerConfigurer = new OAuth2AuthorizationServerConfigurer();
RequestMatcher endpointsMatcher = authorizationServerConfigurer.getEndpointsMatcher();
http      
//Here is my custom form / post login config
.antMatcher("/**")
.formLogin()
.loginPage("/home")
.loginProcessingUrl("/mydomain/login")
.usernameParameter("identifier")
.permitAll()
.and()
.authenticationProvider(customAuthenticationProvider)
.requestMatcher(endpointsMatcher)
.authorizeRequests().antMatchers("/js/**","/assets/**", "/css/**","/home**", "/mydomain/**").permitAll()
.and()
//Extracted from Oauth2 default config``
.authorizeRequests((authorizeRequests) -> {
((ExpressionUrlAuthorizationConfigurer.AuthorizedUrl)authorizeRequests.anyRequest()).authenticated();
})
.csrf((csrf) -> {
csrf.ignoringRequestMatchers(new RequestMatcher[]{endpointsMatcher});
})
.apply(authorizationServerConfigurer);
return  http.build();

谢谢你的帮助!关于

需要实现这样的控制器:


@GetMapping("/login")
public String oauth2LoginPage(Model model,
@CurrentSecurityContext(expression = "authentication") Authentication authentication,
@Value("${spring.security.oauth2.server.login.captcha.enabled:true}") boolean enableCaptchaLogin,
@RequestAttribute(name = "org.springframework.security.web.csrf.CsrfToken", required = false) CsrfToken csrfToken) {
if (!(authentication instanceof AnonymousAuthenticationToken)){
return "redirect:/";
}
if (csrfToken != null) {
model.addAttribute("_csrfToken", csrfToken);
}
SystemSettings systemSettings = new SystemSettings();
model.addAttribute("enableCaptchaLogin",enableCaptchaLogin);
model.addAttribute("systemSettings", systemSettings);
return "oauth2_login";
}

默认HTML表单有几个关键点:

  • 表单应执行张贴到/登录

  • 该表格需要包含一个CSRF令牌,该令牌将自动包括Thymelaf。

  • 表单应在名为username 的参数中指定用户名

  • 表单应在名为password 的参数中指定密码

    如果发现HTTP参数错误,则表示用户未能提供有效的用户名/密码

    如果找到HTTP参数logout,则表示用户已成功注销

参考链接:https://docs.spring.io/spring-security/reference/servlet/authentication/passwords/form.html

相关内容

最新更新