gpt4 book ai didi

java - 无法验证 : HttpSession returned null object for SPRING_SECURITY_CONTEXT

转载 作者:行者123 更新时间:2023-11-30 08:25:04 26 4
gpt4 key购买 nike

目标:我希望允许用户访问我的网络应用程序上的任何页面,/account 页面除外(除非他们已登录) .我希望这个登录过程非常安全,因此转而结合使用 Spring Security 和 BCryptPasswordEncoder 来处理这个过程。此 Web 应用程序是使用 Spring 的纯 Java 方法开发的(没有任何 xml 配置)。

有效方法:转到 /account 会将用户正确重定向到 /login 页面。用户也可以在不被重定向的情况下正确进入/页面。

问题:我正在尝试使用我自己的自定义 UserDetailsS​​ervice 配置 Spring Security,但是每当我尝试通过 JSP View 上的表单登录时, loadUserByUsername(String username) 我在上述 UserDetailsS​​ervice 中覆盖的方法似乎没有被调用。此外,似乎当用户使用假定有效凭据登录时,他们的身份验证不会存储在 Spring Security 的当前 session 中,而是保持 ROLE_ANONYMOUS

WebSecurityConfigurerAdapter:

@EnableWebSecurity
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter
{
@Autowired
private UserDetailsServiceImpl userDetailsServiceImpl;

@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception
{
auth
.userDetailsService(userDetailsServiceImpl)
.passwordEncoder(bCryptPasswordEncoder());
}

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

@Override
protected void configure(HttpSecurity http) throws Exception
{
http
.authorizeRequests()
.antMatchers("/account").hasAnyRole("ROLE_USER", "ROLE_ADMIN")
.anyRequest().authenticated()
.and()
.authorizeRequests()
.antMatchers("/**").permitAll();

http
.formLogin()
.usernameParameter("j_username")
.passwordParameter("j_password")
.loginPage("/login")
.defaultSuccessUrl("/")
.failureUrl("/loginfailed")
.permitAll()
.and()
.logout()
.logoutUrl("/logout")
.logoutSuccessUrl("/")
.permitAll();
}

@Bean @Override
public AuthenticationManager authenticationManagerBean() throws Exception
{
return super.authenticationManagerBean();
}

@Bean
public BCryptPasswordEncoder bCryptPasswordEncoder()
{
return new BCryptPasswordEncoder();
}
}

用户详细信息服务:

@Service("userService")
public class UserDetailsServiceImpl implements UserDetailsService
{
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException
{
username = username.toLowerCase();
try
{
Account account = testAccount(); // See below for more details
if(account == null)
{
throw new UsernameNotFoundException("Could not find user '" + username + "' in the database.");
}

List<GrantedAuthority> auths = new ArrayList<GrantedAuthority>();
for(Role r : account.getRoles())
{
auths.add(new SimpleGrantedAuthority(r.getRole()));
}

WebUser user = null;
try
{
user = new WebUser(account.getUserID(), username, account.getPassword(), true, true, true, true, auths);
}
catch(Exception e)
{
e.printStackTrace();
}

return user;
}
catch(Exception e)
{
e.printStackTrace();
throw new UsernameNotFoundException(username + " not found", e);
}
}

private Account testAccount()
{
Account acc = new Account();
acc.setUserID(1);
acc.setUsername("admin");
acc.setPassword("$2a$10$ETHSfGAR8FpNTyO52O7qKuoo2/8Uqdwcqq70/5PN4.8DXTR6Ktiha");
acc.setDescription("No description.");
acc.setInfluence(9001);
acc.setJoinDate("03-15-2014");
List<Role> roles = new ArrayList<Role>();
roles.add(new Role(Role.ADMIN)); // Role.ADMIN = "ROLE_ADMIN"
roles.add(new Role(Role.USER)); // Role.USER = "ROLE_USER"
return acc;
}
}

登录.jsp:

<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>

<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<base href="${pageContext.request.scheme}://${pageContext.request.serverName}:${pageContext.request.serverPort}${pageContext.request.contextPath}/" />
<title>Login</title>
<link rel="stylesheet" type="text/css" href="css/main.css" />
<script type="text/javascript" src="js/main.js"></script>
</head>

<body onload="document.loginForm.j_username.focus();">
<div id="page_wrap">
<h2><a href="">Login Page</a></h2>
<div id="container">
<div id="login">
<form name="loginForm" action="<c:url value='j_spring_security_check' />" method="POST">
<h5>Log in to your account</h5>
<p>
<label for="name">Username: </label>
<input type="text" name="j_username" />
</p>
<p>
<label for="name">Password: </label>
<input type="password" name="j_password" />
</p>
<p>
<input type="submit" id="submit" value="Log In" name="submit" />
</p>
<input type="hidden" name="${_csrf.parameterName}" value="${_csrf.token}"/>
</form>

<c:if test="${not empty error}">
<div class="errorblock">
Your login attempt was not successful, please try again.<br>
Caused: ${sessionScope["SPRING_SECURITY_LAST_EXCEPTION"].message}
</div>
</c:if>

</div><!--end login-->
</div><!--end container-->
</div><!--end page_wrap-->

</body>
</html>

输入:

用户名输入字段(“j_username”):admin
密码输入字段(“j_password”):密码
注意:我在 UserDetailsS​​erviceImpl 中使用的散列密码是使用 bCryptPasswordEncoder.encode("password");

生成的

结果:保留在 /login 页面上,不会像成功登录时那样重定向到 /

输出:

12726 [http-bio-8080-exec-9] DEBUG org.springframework.security.web.context.HttpSessionSecurityContextRepository  - HttpSession returned null object for SPRING_SECURITY_CONTEXT
12726 [http-bio-8080-exec-9] DEBUG org.springframework.security.web.context.HttpSessionSecurityContextRepository - No SecurityContext was available from the HttpSession: org.apache.catalina.session.StandardSessionFacade@66201d6d. A new one will be created.
...
12727 [http-bio-8080-exec-9] DEBUG org.springframework.security.web.access.intercept.FilterSecurityInterceptor - Secure object: FilterInvocation: URL: /j_spring_security_check; Attributes: [authenticated]
12727 [http-bio-8080-exec-9] DEBUG org.springframework.security.web.access.intercept.FilterSecurityInterceptor - Previously Authenticated: org.springframework.security.authentication.AnonymousAuthenticationToken@6faeba70: Principal: anonymousUser; Credentials: [PROTECTED]; Authenticated: true; Details: org.springframework.security.web.authentication.WebAuthenticationDetails@fffbcba8: RemoteIpAddress: 0:0:0:0:0:0:0:1; SessionId: 9626C55509CC1073AC2B5A8F65B2A585; Granted Authorities: ROLE_ANONYMOUS
12728 [http-bio-8080-exec-9] DEBUG org.springframework.security.access.vote.AffirmativeBased - Voter: org.springframework.security.web.access.expression.WebExpressionVoter@14cef147, returned: -1
12728 [http-bio-8080-exec-9] DEBUG org.springframework.security.web.access.ExceptionTranslationFilter - Access is denied (user is anonymous); redirecting to authentication entry point
org.springframework.security.access.AccessDeniedException: Access is denied

最佳答案

从日志来看,您似乎遇到了对“/j_spring_security_check”的拒绝访问。这是可以理解的,因为您没有将其标记为不 protected 。我认为您可能只是对默认登录处理 URL(/login with @Configuration iirc)做出了错误的假设。如果您发帖到“/login”,它会起作用吗?

关于java - 无法验证 : HttpSession returned null object for SPRING_SECURITY_CONTEXT,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22434738/

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