我正在使用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添加了评论,我打印用户名,我看到一个空字符串即。打印&#34;按用户名加载用户 - &#34;
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);
}
}
这是Application initializer的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));
}
答案 0 :(得分:4)
Spring Security允许您自定义表单登录,但您必须为其设置一些内容,如用户名和密码参数。以下是security-context.xml
中此配置的示例:
<http auto-config="true" use-expressions="true">
<intercept-url pattern="/home**" access="isAuthenticated()" />
<intercept-url pattern="/login" access="permitAll" />
<intercept-url pattern="/" access="isAuthenticated()" />
<form-login login-page="/login"
authentication-failure-url="/login?error=true"
default-target-url="/index"
username-parameter="username"
password-parameter="password"/>
<logout logout-url="/logout" logout-success-url="/login" />
注意有username-parameter
和password-parameter
配置,这可能是您的问题。祝你好运