gpt4 book ai didi

具有 3 个字段身份验证和自定义登录表单的 Spring Boot 安全性

转载 作者:行者123 更新时间:2023-12-05 00:21:57 25 4
gpt4 key购买 nike

我正在使用 spring boot,我需要使用 3 个字段的身份验证过程用户名、密码和公司标识符作为表单中的隐藏输入来实现 spring security。

我实现了一个自定义 usernamepasswordauthenticationfilter 但它似乎不足以设置安全配置。

编辑 :

用户似乎没有经过身份验证!因为可以访问 web 配置中定义的经过身份验证的请求

编辑 2:

在我的自定义过滤器中,当输入有效用户时,它会在 succesfulAuthentication 上执行。我缺少什么,请为我提供任何帮助:(
我在这里

@Repository
public class AuthenticationUserDetailsService implements UserDetailsService {

private static final Logger LOGGER = Logger.getLogger(AuthenticationUserDetailsService.class);

@Autowired
private UserRepository users;

private org.springframework.security.core.userdetails.User userdetails;

@Override
public UserDetails loadUserByUsername(String input) throws UsernameNotFoundException {
// TODO Auto-generated method stub

System.out.println(input);
String[] split = input.split(":");
if (split.length < 2) {
LOGGER.debug("User did not enter both username and corporate domain.");
throw new UsernameNotFoundException("no corporate identifier is specified");
}
String username = split[0];
String corporateId = split[1];

System.out.println("Username = " + username);
System.out.println("Corporate identifier = " + corporateId);

boolean enabled = true;
boolean accountNonExpired = true;
boolean credentialsNonExpired = true;
boolean accountNonLocked = true;

com.ubleam.corporate.server.model.User user;

user = checkUserDetail(username, corporateId);

if (user == null)
throw new NotAuthorizedException("Your are not allowed to access to this resource");

LOGGER.info("User email : " + user.getEmail() + "#User corporate : " + user.getCorporateId());

userdetails = new User(user.getEmail(), user.getPassword(), enabled, accountNonExpired, credentialsNonExpired, accountNonLocked, getAuthorities("ROLE_USER"));
return userdetails;
}

/**
*
* @param roles
* roles granted for user
* @return List of granted authorities
*
*/

public List<GrantedAuthority> getAuthorities(String roles) {

List<GrantedAuthority> authList = new ArrayList<GrantedAuthority>();
authList.add(new SimpleGrantedAuthority(roles));
return authList;
}

/**
* User authentication details from database
*
* @param username
* to use for authentication
* @param coporateId
* corporate identifier of user
* @return found user in database
*/
private com.ubleam.corporate.server.model.User checkUserDetail(String username, String corporateId) {

com.ubleam.corporate.server.model.User user = users.findByEmailAndCorporateId(username, corporateId);

return user;
}

我的自定义过滤器:
public class PlatformAuthenticationFilter extends UsernamePasswordAuthenticationFilter {

private static final Logger LOGGER = Logger.getLogger(PlatformAuthenticationFilter.class);

private static final String LOGIN_SUCCESS_URL = "{0}/bleamcards/{1}/home";
private static final String LOGIN_ERROR_URL = "{0}/bleamcards/{1}/login?error";
private String parameter = "corporateId";
private String delimiter = ":";
private String corporateId;

@Override
protected String obtainUsername(HttpServletRequest request) {
String username = request.getParameter(getUsernameParameter());
String extraInput = request.getParameter(getParameter());

String combinedUsername = username + getDelimiter() + extraInput;

setCorporateId(extraInput);
LOGGER.info("Combined username = " + combinedUsername);
return combinedUsername;
}

@Override
protected void successfulAuthentication(HttpServletRequest request, HttpServletResponse response, Authentication authResult) throws IOException, ServletException {

String contextPath = request.getContextPath();
String url = MessageFormat.format(LOGIN_SUCCESS_URL, contextPath, corporateId);

response.sendRedirect(url);
}

@Override
protected void unsuccessfulAuthentication(HttpServletRequest request, HttpServletResponse response, AuthenticationException failed) throws IOException, ServletException {

String contextPath = request.getContextPath();
String url = MessageFormat.format(LOGIN_ERROR_URL, contextPath, corporateId);

response.sendRedirect(url);
}

public String getParameter() {
return parameter;
}

public void setParameter(String corporateId) {
this.parameter = corporateId;
}

public String getDelimiter() {
return delimiter;
}

public void setDelimiter(String delimiter) {
this.delimiter = delimiter;
}

public String getCorporateId() {
return corporateId;
}

public void setCorporateId(String corporateId) {
this.corporateId = corporateId;
}
}

最后是网络安全配置:
@Configuration
@EnableWebMvcSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

@Inject
private AuthenticationManagerBuilder auth;
@Inject
private UserDetailsService userDS;

@Override
protected void configure(HttpSecurity http) throws Exception {

http.authorizeRequests().antMatchers("/bleamcards/**/login", "/bleamcards/**/forgetpassword", "/bleamcards/**/register", "/css/**", "/js/**", "/images/**", "/webjars/**")
.permitAll().anyRequest().authenticated().and().addFilterBefore(authenticationFilter(), UsernamePasswordAuthenticationFilter.class).formLogin().loginPage("/login")
.defaultSuccessUrl("/").permitAll().and().logout().permitAll();
}

@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth.eraseCredentials(false);
auth.userDetailsService(userDS).passwordEncoder(new BCryptPasswordEncoder());

}

@Bean
@Override
public AuthenticationManager authenticationManager() throws Exception {
return auth.build();
}

@Bean
public PlatformAuthenticationFilter authenticationFilter() throws Exception {
PlatformAuthenticationFilter authFilter = new PlatformAuthenticationFilter();
authFilter.setRequiresAuthenticationRequestMatcher(new AntPathRequestMatcher("/login", "POST"));
authFilter.setAuthenticationManager(authenticationManager());
authFilter.setUsernameParameter("username");
authFilter.setPasswordParameter("password");
authFilter.setParameter("corporateId");
return authFilter;
}

@Override
protected UserDetailsService userDetailsService() {
return userDS;
}

我希望用户只能连接到他们各自公司平台的/login/register/forgetpasswod 网址

最佳答案

实际上,我设法找到了解决我的问题的方法。

我在缺少 successAuthentication 时添加了 successHandler !在 unsuccessfulAuthentication 方法上也有一个 failureHandler。

这是我的新身份验证过滤器:

public class TwoFactorAuthenticationFilter extends UsernamePasswordAuthenticationFilter {

private static final String LOGIN_SUCCESS_URL = "{0}/bleamcards/{1}/home";
private static final String LOGIN_ERROR_URL = "{0}/bleamcards/{1}/login?error";
private String parameter = "corporateId";
private String delimiter = ":";
private String corporateId;


@Override
protected String obtainUsername(HttpServletRequest request) {
String username = request.getParameter(getUsernameParameter());
String extraInput = request.getParameter(getParameter());
String combinedUsername = username + getDelimiter() + extraInput;

setCorporateId(extraInput);
System.out.println("Combined username = " + combinedUsername);
return combinedUsername;
}

@Override
protected void successfulAuthentication(HttpServletRequest request, HttpServletResponse response, FilterChain chain , Authentication authResult) throws IOException, ServletException {

String contextPath = request.getContextPath();
String url = MessageFormat.format(LOGIN_SUCCESS_URL, contextPath, corporateId);
setAuthenticationSuccessHandler(new SimpleUrlAuthenticationSuccessHandler(url));
super.successfulAuthentication(request, response, chain, authResult);

}

@Override
protected void unsuccessfulAuthentication(HttpServletRequest request, HttpServletResponse response, AuthenticationException failed) throws IOException, ServletException {

String contextPath = request.getContextPath();
String url = MessageFormat.format(LOGIN_ERROR_URL, contextPath, corporateId);
setAuthenticationFailureHandler(new SimpleUrlAuthenticationFailureHandler(url));

super.unsuccessfulAuthentication(request, response, failed);
}

public String getParameter() {
return parameter;
}

public void setParameter(String corporateId) {
this.parameter = corporateId;
}

public String getDelimiter() {
return delimiter;
}

public void setDelimiter(String delimiter) {
this.delimiter = delimiter;
}

public String getCorporateId() {
return corporateId;
}

public void setCorporateId(String corporateId) {
this.corporateId = corporateId;
}
}

关于具有 3 个字段身份验证和自定义登录表单的 Spring Boot 安全性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30663527/

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