【发布时间】:2014-04-21 11:59:32
【问题描述】:
目标:我希望允许用户访问我的 web 应用程序上的任何页面,/account 页面除外(除非他们已登录)。我希望这个登录过程非常安全,因此转而使用 Spring Security 和 BCryptPasswordEncoder 来处理这个过程。这个 webapp 正在使用 Spring 的 pure-Java 方法(没有任何 xml 配置)开发。
什么有效:转到/account 正确地将用户重定向到/login 页面。用户也可以在不被重定向的情况下正确访问/页面。
问题:我正在尝试使用我自己的自定义 UserDetailsService 配置 Spring Security,但是每当我尝试通过我的 JSP 视图上的表单登录时,loadUserByUsername(String username) 方法我改写了说UserDetailsService 似乎没有被调用。此外,似乎当用户使用 supposedly 有效凭据登录时,他们的身份验证并未存储在 Spring Security 的当前会话中,而是保留为 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();
}
}
UserDetailsService:
@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;
}
}
login.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”):密码
注意:我在 UserDetailsServiceImpl 中使用的哈希密码是使用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
【问题讨论】:
标签: java spring spring-mvc spring-security