gpt4 book ai didi

java - Spring 安全: make every page redirect if the user doesn't meet a specific criteria

转载 作者:行者123 更新时间:2023-12-02 04:51:55 25 4
gpt4 key购买 nike

我正在开发一个使用 Spring Security 作为身份验证/授权提供程序的 Web 应用程序。这是我的配置方法:

@Override
protected void configure(HttpSecurity http) throws Exception
{
http
.authorizeRequests()

//Allow resources for all pages
.antMatchers("/css/**", "/images/**", "/webjars/**").permitAll()

//Allow or disallow specific routes depending on user privileges

//Users
.antMatchers("/users/", "users/search").hasAuthority("View Users")
.antMatchers("/users/add", "/users/edit/*", "/users/delete/*").hasAuthority("Edit Users")

.antMatchers("/roles/", "roles/search").hasAuthority("View Roles")
.antMatchers("/roles/add", "/roles/edit/*", "/roles/delete/*").hasAuthority("Edit Roles")

.antMatchers("/permissions/", "permissions/search").hasAuthority("View Permissions")

//A million other antMatchers here...

//All custom routes require authentication
.anyRequest().authenticated()

//Custom login page and handling
.and()
.formLogin()
.loginPage("/login")
.loginProcessingUrl("/perform_login")
.successHandler(loginHandler())
.failureUrl("/login_error")
.permitAll()

//Custom logout handling with POST request and logout handler for auditing
.and()
.logout()
.logoutRequestMatcher(new AntPathRequestMatcher("/logout"))
.logoutSuccessHandler(logoutHandler())
.logoutSuccessUrl("/logout_success")
.permitAll()

//Invalidate the session and delete the JSESSIONID cookie on logout
.invalidateHttpSession(true)
.deleteCookies("JSESSIONID");
}

我不想发布太多代码(如果需要的话我会发布),但本质上我的用户存储在数据库中,并且我使用 UserDetails 和 UserDetailsS​​ervice 的扩展在 Spring Security 和数据库之间进行交互。在我的用户实体中,我有一个 boolean 字段,用于控制用户是否需要更改其密码(首次登录)。为了在用户登录时实现此功能,我有以下 AuthenticationSuccessHandler :

    public class LoginHandler implements AuthenticationSuccessHandler
{
@Autowired
private UserService userService;

@Autowired
private PreferenceService preferenceService;

@Override
public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
Authentication authentication) throws IOException, ServletException
{
User user = userService.findById(((UserDetails) authentication.getPrincipal()).getId());

if (user.isMustChangePassword())
{
response.sendRedirect(request.getContextPath() + "/users/initialPasswordChange");
}
else
{
response.sendRedirect(request.getContextPath() + getAnchorPageURL(user));
}
}
}

登录时效果非常好,行为完全符合我的要求。初始密码更改页面没有菜单,但没有什么可以阻止用户修改 URL 并在不更改密码的情况下登陆主页。在以前的 Spring MVC 时代,我会构建一个在每个页面上运行的自定义 Filter 类,该类将检查登录的用户是否将该字段设置为 true 并重定向到初始密码更改页面。这样,无论用户做什么,在更改密码之前整个网站都将无法访问。

现在有没有更优雅的、Spring Security-ey 的方法来做到这一点?

如果有帮助的话,我将再次提供更多代码,不想淹没我的帖子,并希望首先包含最相关的部分。

最佳答案

这适用于旧的 Spring MVC Filter 方法。有没有更好的、纯粹的 Spring Security 方法来做到这一点?

@Component
@WebFilter(urlPatterns = {"/*"}, description = "initialPasswordChangeFilter")
public class InitialPasswordChangeFilter implements Filter
{
@Autowired
private UserService userService;

@Override
public void init(FilterConfig fc) throws ServletException
{
SpringBeanAutowiringSupport.processInjectionBasedOnCurrentContext(this);

Filter.super.init(fc);
}

@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException
{
HttpServletRequest req = (HttpServletRequest) request;
HttpServletResponse res = (HttpServletResponse) response;

try
{
SecurityContextImpl sci = (SecurityContextImpl) req.getSession(false).getAttribute("SPRING_SECURITY_CONTEXT");

User user = userService.findById(((UserDetails) sci.getAuthentication().getPrincipal()).getId());

String url = req.getRequestURL().toString();

if (user.isMustChangePassword() && !url.contains("initial") && !url.contains("/webjars") && !url.contains("/css") &&
!url.contains("/js") && !url.contains("/images"))
{
res.sendRedirect(req.getContextPath() + "/users/initialPasswordChange");
}
else
{
chain.doFilter(request, response);
}
}
catch (NullPointerException ex)
{
chain.doFilter(request, response);
}
}
}

关于java - Spring 安全: make every page redirect if the user doesn't meet a specific criteria,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56432445/

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