gpt4 book ai didi

java - 没有 web.xml 的 Spring 安全自定义身份验证过滤器

转载 作者:塔克拉玛干 更新时间:2023-11-03 05:32:58 25 4
gpt4 key购买 nike

使用注释和 java 配置,我不太清楚如何为 spring 安全注册一个覆盖的过滤器。

我想要实现的是在不显示登录表单的情况下进行自动登录,因为那时用户已经通过身份验证。因此只会读取 header 参数并使用 spring security 进行授权。

这是我正在尝试的简化版本,除了有时会显示登录屏幕外,Spring 安全性工作正常。引导 BypassLoginFilter 是我需要做的一切。另请阅读某处,对于这种行为,应该关闭 http 自动配置,但不确定如何在纯 java 配置中实现。

SecurityWebApplicationInitializer.java

import org.springframework.security.web.context.AbstractSecurityWebApplicationInitializer;

public class SecurityWebApplicationInitializer extends AbstractSecurityWebApplicationInitializer{

}

安全配置.java

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.web.authentication.logout.LogoutFilter;

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(securedEnabled=true, prePostEnabled=true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {

@Override
public void configure(WebSecurity web) throws Exception {
web.ignoring().antMatchers("/resources/**");
}

@Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable();
http.authorizeRequests().antMatchers("/*").permitAll()
.anyRequest().hasRole("USER").and()
.formLogin()
.permitAll();
http.addFilterBefore(new BypassLoginFilter(), LogoutFilter.class);
//.and().anonymous().disable();
}

@Override
@Autowired
protected void registerAuthentication(AuthenticationManagerBuilder auth) {
try {
auth.inMemoryAuthentication().withUser("user").password("password")
.roles("USER").and().withUser("admin").password("password")
.roles("USER", "ADMIN");
} catch (Exception e) {
e.printStackTrace();
}
}
}

BypassLoginFilter.java

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter;
import org.springframework.security.web.authentication.preauth.PreAuthenticatedAuthenticationToken;

public class BypassLoginFilter extends AbstractAuthenticationProcessingFilter{

private static String HEADER_IS_ADMIN = "isAdmin";

public BypassLoginFilter()
{
super("/*");
}

//Never gets executed
@Override
public Authentication attemptAuthentication(HttpServletRequest request,
HttpServletResponse response) throws AuthenticationException,
IOException, ServletException {

boolean isAdmin = Boolean.valueOf(request.getHeader(HEADER_IS_ADMIN));

PreAuthenticatedAuthenticationToken authRequest = new PreAuthenticatedAuthenticationToken("","",getAuthorities(isAdmin));
authRequest.setDetails(authenticationDetailsSource.buildDetails(request));

return getAuthenticationManager().authenticate(authRequest);
}

private List<GrantedAuthority> getAuthorities(boolean isAdmin)
{
List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();

authorities.add(new SimpleGrantedAuthority("ROLE_USER"));
if(isAdmin){
authorities.add(new SimpleGrantedAuthority("ROLE_ADMIN"));
}
return authorities;
}
}

最佳答案

您可以尝试以下方法。假设您有一个如下所示的 YourUser 类:

public class YourUser extends org.springframework.security.core.userdetails.User{
...
public String getStartPage(){ return "/userhomepage"; }
...
}

然后您需要声明身份验证处理程序:

@Component
public class YourAuthenticationSuccessHandler extends SavedRequestAwareAuthenticationSuccessHandler {

protected String determineTargetUrl(HttpServletRequest request, HttpServletResponse response) {
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
if (authentication.getPrincipal() instanceof YourUser) {
final YourUser user = (YourUser) authentication.getPrincipal();
return user.getStartPage();
}else {
return "/defaultPageForNonAuthenticatedUsers";
}
}
}

并在安全配置中使用它:

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

@Override
protected void configure(HttpSecurity http) throws Exception {
// rest calls are ommited
http.successHandler(successHandler());
}

@Bean
public AuthenticationSuccessHandler successHandler() throws Exception {
return new YourAuthenticationSuccessHandler();
}
}

关于java - 没有 web.xml 的 Spring 安全自定义身份验证过滤器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18784652/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com