gpt4 book ai didi

java - Spring Security Java 配置不会拦截访问仅适用于经过身份验证的源的 JSP 的请求

转载 作者:塔克拉玛干 更新时间:2023-11-02 19:51:04 26 4
gpt4 key购买 nike

我正在制作一个 Spring MVC 网络应用程序。我有一个登录页面和一个仪表板页面。任何试图访问仪表板 JSP 的人都必须登录:

这是我的 Spring Security 配置:

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity
@Import({SpringConfiguration.class})
public class SecurityContext extends WebSecurityConfigurerAdapter {

@Autowired
private DataSource dataSource;

// authorizeRequests() -> use-expresions = "true"
@Override
protected void configure(HttpSecurity http) throws Exception {

http
.authorizeRequests()
.antMatchers("/createaccount","/error", "/register", "/login", "/newaccount", "/resources/**").permitAll()
.antMatchers("/**", "/*", "/").authenticated()
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage("/login")
.defaultSuccessUrl("/dashboard")
.loginProcessingUrl("/j_spring_security_check")
.usernameParameter("username")
.passwordParameter("password")
.failureUrl("/login?error=true")
.and()
.logout()
.logoutUrl("/logout")
.logoutSuccessUrl("/login")
.invalidateHttpSession(true)
.and()
.csrf();

// Upon starting the application, it prints the asdfasdf so I know the SecurityContext is loaded
System.out.println("asdfasdf");
}


// Equivalent of jdbc-user-service in XML
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {

auth
.jdbcAuthentication()
.dataSource(dataSource)
.usersByUsernameQuery("SELECT username, password, enabled FROM Users WHERE username=?")
.authoritiesByUsernameQuery("SELECT username, authority FROM authorities where username=?");
}
}

如您所见,我有一些端点允许任何人访问,例如 /login/register,但所有其他 URL 都要求它们经过身份验证。当我启动应用程序时,如果我尝试转到仪表板页面,我可以很好地访问它而无需登录,这不是我想要的。

我的问题是,我希望尝试访问仪表板的人在未登录/未通过身份验证的情况下被发送到登录页面。

我试图完全避免使用 XML,只使用 Java 来配置我的应用程序,有人知道我做错了什么吗?我几乎可以肯定我的 SecurityContext 有问题。

我也可以包含上下文 XML,我正在尝试将其转换为 Java 配置样式

<security:authentication-manager>
<security:jdbc-user-service
data-source-ref="dataSource"
users-by-username-query="select username, password, enabled from Users where username=?"
authorities-by-username-query="select username, authority from Authority where username =? " />
</security:authentication-provider>
</security:authentication-manager>

<security:http use-expressions="true">

<security:intercept-url pattern="/newaccount"
access="permitAll" />
<security:intercept-url pattern="/accountcreated"
access="permitAll" />
<security:intercept-url pattern="/createaccount"
access="permitAll" />
<security:intercept-url pattern="/error"
access="permitAll" />
<security:intercept-url pattern="/resources/**"
access="permitAll" />
<security:intercept-url pattern="/login"
access="permitAll" />
<security:intercept-url pattern="/setemote"
access="isAuthenticated()" />
<security:intercept-url pattern="/**"
access="isAuthenticated()" />
<security:intercept-url pattern="/*"
access="isAuthenticated()" />


<security:form-login login-page="/login"
default-target-url="/" login-processing-url="/j_spring_security_check"
username-parameter="username" password-parameter="password"
authentication-failure-url="/login?error=true" />
<security:csrf />

</security:http>

最佳答案

美好的一天。

你必须确保你有 SecurityWebApplicationInitializer,看起来像这样:

public class SecurityWebApplicationInitializer extends AbstractSecurityWebApplicationInitializer {
public SecurityWebApplicationInitializer() {
super(SecurityContext.class);
}
}

SecurityContext - 是您的类扩展 WebSecurityConfigurerAdapter

如果您已经拥有它,那么问题可能在于缺少角色。

要拥有角色,您可能希望以不同的方式实现配置,例如:

    .antMatchers("/restricted_area/*")
.access("hasRole('ADMIN')")
.and()
.formLogin()
.loginPage("/login")
.usernameParameter("username")
.passwordParameter("password")
.successHandler(authenticationSuccessHandler)
.permitAll()
.and()
.logout()
.permitAll();

为了处理角色和身份验证,您可以扩展 org.springframework.security.core.userdetails.UserDetailsS​​ervice 有一个单独的类,可以与 Spring 的授权/身份验证机制一起检查凭据。

如您所见,我这里也有 authenticationSuccessHandler。这实际上是扩展

org.springframework.security.web.authentication.AuthenticationSuccessHandler

它所做的是根据角色重定向到特定页面:例如普通用户到用户的仪表板,管理员到管理员的仪表板。虽然不确定这是否与您的问题相关,但实现是这样的:

@Component("customHandler")
public class CustomAuthenticationHandler implements AuthenticationSuccessHandler {
private static final Logger logger = LoggerFactory.getLogger(CustomAuthenticationHandler.class);

private RedirectStrategy redirectStrategy = new DefaultRedirectStrategy();

@Autowired
private UserService userService;

@Override
public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
Authentication authentication) throws IOException {
Object principal = authentication.getPrincipal();
String username = ((UserDetails) principal).getUsername();
userService.updateLastLoginTimeByName(username);
handle(request, response, authentication);
clearAuthenticationAttributes(request);
}

protected void handle(HttpServletRequest request, HttpServletResponse response, Authentication authentication)
throws IOException {
String targetUrl = determineTargetUrl(authentication);

if (response.isCommitted()) {
logger.debug("Response has already been committed. Unable to redirect to " + targetUrl);
return;
}

redirectStrategy.sendRedirect(request, response, targetUrl);
}

/**
* Builds the target URL according to the logic defined in the main class
* Javadoc.
*/
protected String determineTargetUrl(Authentication authentication) {
boolean isAdmin = false;
Collection<? extends GrantedAuthority> authorities = authentication.getAuthorities();
for (GrantedAuthority grantedAuthority : authorities) {
if (grantedAuthority.getAuthority().equals("ROLE_ADMIN")) {
isAdmin = true;
break;
}
}

if (isAdmin) {
return "/restricted_area/";
} else {
throw new IllegalStateException();
}
}

protected void clearAuthenticationAttributes(HttpServletRequest request) {
HttpSession session = request.getSession(false);
if (session == null) {
return;
}
session.removeAttribute(WebAttributes.AUTHENTICATION_EXCEPTION);
}

public void setRedirectStrategy(RedirectStrategy redirectStrategy) {
this.redirectStrategy = redirectStrategy;
}

protected RedirectStrategy getRedirectStrategy() {
return redirectStrategy;
}
}

关于java - Spring Security Java 配置不会拦截访问仅适用于经过身份验证的源的 JSP 的请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42420755/

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