gpt4 book ai didi

java - UserDetailsS​​erviceImpl 中的 loadUserByUsername 中的用户名字段为空

转载 作者:搜寻专家 更新时间:2023-11-01 02:44:41 25 4
gpt4 key购买 nike

我正在使用 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));
}

最佳答案

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-parameterpassword-parameter 配置,这可能是你的问题。祝你好运

关于java - UserDetailsS​​erviceImpl 中的 loadUserByUsername 中的用户名字段为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25462531/

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