【发布时间】:2017-11-05 03:31:04
【问题描述】:
我正在使用 Spring Security 进行身份验证。 问题是我一直将用户名作为空字符串。我什至搜索它我得到的只是我必须遵循我已经在做的 j_username 和 j_password 等字段的标准名称。
这是我的登录页面 -
<form id="signin" role="form" name="loginForm" method="POST"
action='<c:url value="j_spring_security_check"></c:url>'>
<input type="hidden" name="${_csrf.parameterName}" value="${_csrf.token}"/>
<fieldset>
<legend><spring:message code="login.form.head.social.msg" text="Sign in with your social account"></spring:message></legend>
<a href='<c:url value="/auth/facebook"></c:url>'
class="btn social icon-facebook col-lg-5 col-md-5 col-sm-5 col-xs-5 pull-right">
<i class="fa fa-facebook-square fa-2x pull-left"></i>
<spring:message code="login.social.facebook"></spring:message>
</a> <a href="#"
class="btn social icon-gplus col-lg-5 col-md-5 col-sm-5 col-xs-5"><i
class="fa fa-google-plus-square fa-2x pull-left"></i><spring:message code="login.social.googleplus"></spring:message> </a>
</fieldset>
<hr>
<fieldset style="margin-top: 20px;">
<legend>
<spring:message code="login.form.head.register.msg" text="Login with your registered account"></spring:message>
</legend>
<div class="form-group">
<div class="input-group">
<span class="input-group-addon">@</span> <input type="email"
class="form-control" id="email" placeholder='<spring:message code="placeholder.email" text="Password"></spring:message>'
name="j_username">
</div>
</div>
<div class="form-group">
<div class="input-group">
<span class="input-group-addon"><i
class="fa fa-key fa-rotate-90"></i></span> <input type="password"
class="form-control" id="password" placeholder="<spring:message code="placeholder.password" text="Password"></spring:message>"
name="j_password">
</div>
</div>
<div class="form-group">
<div class="input-group">
<button type="submit"
class="btn btn-primary pull-right col-lg-4 col-md-4 col-sm-4 col-xs-4">
<spring:message code="btn.login" text="Login"></spring:message>
</button>
<div class="checkbox">
<label> <input type="checkbox" id="remember-me"
name="_spring_security_remember_me">
<spring:message code="link.rememberme" text="Remember me"></spring:message>
</label>
</div>
</div>
</div>
<div class="form-group">
<div class="input-group">
<a href="#" class="login-link">
<spring:message code="link.resetpassword" text="Reset password !"></spring:message>
</a> <a href="#"
class="login-link pull-right">
<spring:message code="link.registerhere" text="Register here !"></spring:message>
</a>
</div>
</div>
</fieldset>
</form>
我的 loadUserByUsername 方法。 我在 logger.info 添加了评论,我在其中打印用户名,我看到一个空字符串,即。打印“通过用户名加载用户-”
public UserDetails loadUserByUsername(String username)
throws UsernameNotFoundException {
// TODO Auto-generated method stub
logger.info("load user by username - "+username); //Here username is blank
User user = getUserByEmail(username);
if (user == null) {
throw new UsernameNotFoundException("No user found with username: " + username);
}
SimpleUserDetailsVO principal = SimpleUserDetailsVO.getBuilder()
.firstName(user.getFname())
.id(user.getId())
.lastName(user.getLname())
.password(user.getPassword())
.role(user.getRole())
.socialSignInProvider(user.getSignInProvider())
.username(user.getEmail())
.build();
return principal;
}
在这种方法中,我记录了用户名并获得了空字符串。
这是我的安全上下文
@Configuration
@EnableWebSecurity
public class SecurityContext extends WebSecurityConfigurerAdapter{
@Autowired
private UserServiceImpl userServiceImpl;
@Autowired
private CustomAuthenticationSuccessHandler customAuthenticationSuccessHandler;
public void configure(WebSecurity web) throws Exception {
web
//Spring Security ignores request to static resources such as CSS or JS files.
.ignoring()
.antMatchers("/resources/**");
}
protected void configure(HttpSecurity http) throws Exception {
http
//Configures form login
.formLogin()
.loginPage("/Home")
.failureUrl("/Home?loginError=true")
.successHandler(customAuthenticationSuccessHandler)
.defaultSuccessUrl("/Home")
.loginProcessingUrl("/j_spring_security_check")
//Configures the logout function
.and()
.logout()
.deleteCookies("JSESSIONID")
.logoutUrl("/j_spring_security_logout")
.logoutSuccessUrl("/Home?logout=true")
.invalidateHttpSession(true)
//Configures url based authorization
.and()
.authorizeRequests()
//Anyone can access the urls
.antMatchers(
"/Home"
).permitAll()
//The rest of the our application is protected.
.antMatchers("/Admin/**").hasRole("ADMIN")
.antMatchers("/Learner/**").hasRole("LEARNER")
.antMatchers("/Teacher/**").hasRole("TEACHER")
.antMatchers("/Institute/**").hasRole("INSTITUTE")
//Adds the SocialAuthenticationFilter to Spring Security's filter chain.
.and()
.apply(new SpringSocialConfigurer());
}
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth
.userDetailsService(userServiceImpl)
.passwordEncoder(passwordEncoder());
}
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder(10);
}
}
这里是应用初始化器的 onStartup 方法
public void onStartup(ServletContext servletContext)
throws ServletException {
AnnotationConfigWebApplicationContext rootContext = new AnnotationConfigWebApplicationContext();
rootContext.register(MyApplicationContext.class);
rootContext.setServletContext(servletContext);
ServletRegistration.Dynamic dispatcher = servletContext.addServlet("dispatcher", new DispatcherServlet(rootContext));
dispatcher.setLoadOnStartup(1);
dispatcher.addMapping("/");
EnumSet<DispatcherType> dispatcherTypes = EnumSet.of(DispatcherType.REQUEST, DispatcherType.FORWARD);
CharacterEncodingFilter characterEncodingFilter = new CharacterEncodingFilter();
characterEncodingFilter.setEncoding("UTF-8");
characterEncodingFilter.setForceEncoding(true);
FilterRegistration.Dynamic characterEncoding = servletContext.addFilter("characterEncoding", characterEncodingFilter);
characterEncoding.addMappingForUrlPatterns(dispatcherTypes, true, "/*");
FilterRegistration.Dynamic security = servletContext.addFilter("springSecurityFilterChain", new DelegatingFilterProxy());
security.addMappingForUrlPatterns(dispatcherTypes, true, "/*");
// FilterRegistration.Dynamic sitemesh = servletContext.addFilter("sitemesh", new ConfigurableSiteMeshFilter());
// sitemesh.addMappingForUrlPatterns(dispatcherTypes, true, "/");
servletContext.addListener(new ContextLoaderListener(rootContext));
}
【问题讨论】:
-
不知道为什么用户名是空的。您能否在调试级别记录软件包
org.springframework.security的登录请求并将其包含在您的问题中? -
@Ravi Kumar:我也面临类似的问题。你找到解决方案了吗?
-
在我的情况下这是一个拼写错误@Ashwin
标签: java spring spring-mvc spring-security