繁体   English   中英

Spring Security 自定义登录和自定义身份验证提供程序

[英]Spring Security Custom Login And Custom Authentication Provider

我正在创建一个带有 spring 安全登录的项目,这是我项目的一部分,我想使用自定义登录页面和自定义身份验证提供程序我已经搜索了教程,但我在显示的自定义登录页面中结束了,但是,用户无法登录,(拒绝访问)在堆栈跟踪中收到,这是我的代码,我更喜欢完整的 java 配置。

这是我的安全配置类

@Configuration
@EnableWebSecurity
@ComponentScan("id.config.configPack")
public class SecurityConfig extends WebSecurityConfigurerAdapter{


 @Autowired
    private CustomAuthenticationProvider authProvider;

    @Override
    protected void configure(
      AuthenticationManagerBuilder auth) throws Exception {
        auth.authenticationProvider(authProvider);
    }

@Override
public void configure(HttpSecurity http) throws Exception {
         http.csrf().disable();
         http
            .authorizeRequests()
                .antMatchers("/resources/**").permitAll()
                .anyRequest().authenticated()
                .and()
            .formLogin()
                .loginPage("/login")
                .defaultSuccessUrl("/menu")
                .permitAll()
                .and()
            .logout()                                    
                .permitAll();

}

}

这是为了初始化项目

public class SecurityWebApplicationInitializer extends 
AbstractSecurityWebApplicationInitializer {

public SecurityWebApplicationInitializer() {
    super(SecurityConfig.class);
}
}

这是我的自定义身份验证提供程序

@Component
public class CustomAuthenticationProvider implements AuthenticationProvider {

@Override
public Authentication authenticate(Authentication authentication) 
  throws AuthenticationException {

    String user = authentication.getName();
    String password = authentication.getCredentials().toString();
    List<GrantedAuthority> grantedAuths = new ArrayList<>();
    grantedAuths.add(new SimpleGrantedAuthority("ROLE_USER"));
    if (user.equalsIgnoreCase("test") && password.equals("test")) {        
        return new UsernamePasswordAuthenticationToken
                (user, password, grantedAuths);
    } else {
        throw new BadCredentialsException("Authentication failed");
    }

}

@Override
public boolean supports(Class<?> authentication) {
    return authentication.equals(
      UsernamePasswordAuthenticationToken.class);
}
}

这是我的登录页面,我没有指定操作,因为据我所知,spring security 控制了它,CMIW。

<form id="loginForm" class="login-form">
    <input name="username" type="text" placeholder="Username" />
    <input name="password" type="password" placeholder="Password" />
    <button type="submit">Submit</button>
    <br />
    <br />
    <span id="err" class="errMsg"></span>
</form>

我还为登录页面和成功登录页面定义了一个控制器类。

我的预期结果是我可以登录并重定向到我的安全配置中的默认登录成功处理程序,是否缺少或需要任何代码? 谢谢

不,动作必须是登录,方法必须是发布,或者你可以像那样 ovveride 动作。formLogin().loginPage("/login").loginProcessingUrl("/auth")

你需要添加东西到 java 类:

@Configuration
@EnableWebSecurity
public class BasicAuthConfiguration extends WebSecurityConfigurerAdapter {

@Override
protected void configure(final HttpSecurity http) throws Exception {
    http.csrf().disable()
            .authorizeRequests()
            .anyRequest().authenticated()

            .and()
            .formLogin()
            .loginPage("/loginPage")
            .loginProcessingUrl("/auth")
            .successHandler(successHandler())
            .failureHandler(failureHandler())
            .permitAll()

            .and()
            .logout()
            .logoutSuccessHandler(new HttpStatusReturningLogoutSuccessHandler(HttpStatus.OK))
            .deleteCookies("JSESSIONID")
            .invalidateHttpSession(true)
            .permitAll();
}

@Bean
public AuthenticationProvider authenticationProvider() {
    return new CustomAuthenticationProvider();
}

@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
    auth.authenticationProvider(authenticationProvider());
}

private AuthenticationEntryPoint getRestAuthenticationEntryPoint() {
    return new HttpStatusEntryPoint(HttpStatus.UNAUTHORIZED);
}

@Override
public void configure(WebSecurity web) throws Exception {
    web.ignoring().antMatchers("/app/dist/*");
}

private AuthenticationSuccessHandler successHandler() {
    return new AuthenticationSuccessHandler() {
        @Override
        public void onAuthenticationSuccess(HttpServletRequest httpServletRequest,
                                            HttpServletResponse httpServletResponse, Authentication authentication)
                throws IOException, ServletException {
            httpServletResponse.setStatus(200);
            Collection<? extends GrantedAuthority> authorities = authentication.getAuthorities();
            if(authorities.toString().contains("ROLE_ADMIN")){
                httpServletResponse.setHeader("role", "ROLE_ADMIN");
            } else if(authorities.toString().contains("ROLE_NOPRICED")){
                httpServletResponse.setHeader("role", "ROLE_NOPRICED");
            }
        }
    };
}

private AuthenticationFailureHandler failureHandler() {
    return new AuthenticationFailureHandler() {
        @Override
        public void onAuthenticationFailure(HttpServletRequest httpServletRequest,
                                            HttpServletResponse httpServletResponse, AuthenticationException e)
                throws IOException, ServletException {
            httpServletResponse.setStatus(401);
        }
    };
}

}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM