一尘不染

用于Spring 4.0 + Security 3.2 + j_spring_security_check的JavaConfiguration

spring-mvc

  1. 创建一个登录页面

```
<%@ taglib prefix=”c” uri="http://java.sun.com/jsp/jstl/core” %>
<!DOCTYPE html>



Test




Login

" method="POST">
 

 

 






Failed to login.

Reason:








  2. 声明WebSecurityConfigurer在 **这里我遗漏了j_username和j_password**

@Configuration
@EnableWebSecurity
@ComponentScan(basePackages = {“com.sample.init.security”})
public class WebSecurityConfigurer extends WebSecurityConfigurerAdapter {

@Inject
private AuthenticationProvider authenticationProvider;

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

@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers(
“/resources/”,
“/static/
”,
“/j_spring_security_check”,
“/AppController/echo.html”).permitAll()
.anyRequest().authenticated()
.and()
.formLogin()
.usernameParameter(“j_username”) / BY DEFAULT IS username!!! /
.passwordParameter(“j_password”) / BY DEFAULT IS password!!! /
.loginProcessingUrl(“/j_spring_security_check”)
.loginPage(“/”)
.defaultSuccessUrl(“/page”)
.permitAll()
.and()
.logout()
.permitAll();
}

@Override
public void configure(WebSecurity web) throws Exception {
web
.ignoring()
.antMatchers(“/static/**”);
}

}



  3. 声明一个WebMvcConfigurer

@EnableWebMvc
@Configuration
@ComponentScan(basePackages = {
“com.app.controller”,
“com.app.service”,
“com.app.dao”
})
public class WebMvcConfigurer extends WebMvcConfigurerAdapter {

@Bean
public ViewResolver viewResolver() {
InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
viewResolver.setPrefix(“/WEB-INF/view/”);
viewResolver.setSuffix(“.jsp”);
return viewResolver;
}

@Override
public void addViewControllers(ViewControllerRegistry registry) {
registry.addViewController(“/page”).setViewName(“page”);
}

@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler(“static/**”).addResourceLocations(“static/”);
}

}

```

  1. 声明安全初始化程序

    public class SecurityWebAppInitializer 
    extends AbstractSecurityWebApplicationInitializer { }
    
  2. 声明一个应用初始化器

    public class Initializer extends AbstractAnnotationConfigDispatcherServletInitializer  {
    
    @Override
    protected Class<?>[] getRootConfigClasses() {       
        return new Class<?>[]{WebSecurityConfigurer.class};
    }
    
    @Override
    protected Class<?>[] getServletConfigClasses() {
        return new Class<?>[]{WebMvcConfigurer.class, DataSourceConfigurer.class};
    }
    
    @Override
    protected String[] getServletMappings() {
        return new String[]{"/"};
    }
    

    }

  3. 实施您的自定义身份验证提供程序

    @Component
    

    @ComponentScan(basePackages = {“com.app.service”})
    public class CustomAuthenticationProvider implements AuthenticationProvider {

    private static final Logger LOG = LoggerFactory.getLogger(CustomAuthenticationProvider.class);
    
    @Inject
    private AppService service;
    
    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
    
        //Thread.dumpStack();
        String username = authentication.getName();
        String password = authentication.getCredentials().toString();
    
        String message = String.format("Username: '%s' Password: '%s'", username, password);
        UserBean userBean = service.validate(username, password);       
        LOG.debug(message);
        if (userBean != null) {
            List<GrantedAuthority> grantedAuths = new ArrayList<>();
            grantedAuths.add(new SimpleGrantedAuthority("USER"));
            return new UsernamePasswordAuthenticationToken(userBean, authentication, grantedAuths); 
        } else {
            String error = String.format("Invalid credentials [%s]", message);
            throw new BadCredentialsException(error);
        }
    }
    
    @Override
    public boolean supports(Class<?> authentication) {
        return authentication.equals(UsernamePasswordAuthenticationToken.class);
    }
    

    }

我跳过了EchoController,AppService,AppDao和UserBean。

谢谢。


阅读 299

收藏
2020-06-01

共1个答案

一尘不染

在3.2版本中,post参数已从j_username更改为username,而j_password更改为password。登录网址也已从/
j_spring_security_check更改为/ login。

请参阅此链接以了解实施此更改的原因:http :
//docs.spring.io/spring-
security/site/docs/3.2.0.RELEASE/reference/htmlsingle/#jc-
httpsecurity
。这些是更改:

  • GET / login呈现登录页面,而不是/ spring_security_login

  • POST / login验证用户身份,而不是/ j_spring_security_check

  • username参数默认为username而不是j_username

  • password参数默认为password而不是j_password

以下是登录表单的示例:http :
//docs.spring.io/spring-
security/site/docs/3.2.0.RELEASE/reference/htmlsingle/#jc-
form

2020-06-01