JavaConfiguration for Spring 4.0 + Security 3.2 + j_spring_security_check [英] JavaConfiguration for Spring 4.0 + Security 3.2 + j_spring_security_check

查看:24
本文介绍了JavaConfiguration for Spring 4.0 + Security 3.2 + j_spring_security_check的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  1. 创建登录页面

    <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %><!DOCTYPE html><头><meta charset="ISO-8859-1"><title>测试</title><script src="static/js/jquery-1.10.2.min.js"></script><script src="static/js/app-controller.js"></script><身体><div>登录</div><form name="f" action="<c:url value="/j_spring_security_check"/>"方法=POST"><label for="password">用户名</label><input type="text" id="j_username" name="j_username"><br/><label for="password">密码</label><input type="password" id="j_password" name="j_password"><br/><input type="submit" value="Validate"><input name="reset" type="reset"><input type="hidden" id="${_csrf.parameterName}" name="${_csrf.parameterName}" value="${_csrf.token}"/></表单><小时/><c:if test="${param.error != null}"><div>登录失败.<c:if test="${SPRING_SECURITY_LAST_EXCEPTION != null}">原因:<c:out value="${SPRING_SECURITY_LAST_EXCEPTION.message}"/></c:if>

</c:if><小时/><input type="button" value="Echo" id="echo" name="echo" onclick="AppController.echo();"><div id="echoContainer"></div>

  • 声明一个 WebSecurityConfigurer 这里是我缺少 j_username 和 j_password 的地方

    @Configuration@启用网络安全@ComponentScan(basePackages = {"com.sample.init.security"})公共类 WebSecurityConfigurer 扩展了 WebSecurityConfigurerAdapter {@注入私有 AuthenticationProvider 身份验证提供者;@注入public void configureGlobal(AuthenticationManagerBuilder auth) 抛出异常 {auth.authenticationProvider(authenticationProvider);}@覆盖protected void configure(HttpSecurity http) 抛出异常 {http.authorizeRequests().antMatchers(/资源/**",/静止的/**","/j_spring_security_check","/AppController/echo.html").permitAll().anyRequest().authenticated().和().formLogin().usernameParameter("j_username")/* 默认是用户名!!!*/.passwordParameter("j_password")/* 默认是密码!!!*/.loginProcessingUrl("/j_spring_security_check").loginPage("/").defaultSuccessUrl("/page").permitAll().和().登出().permitAll();}@覆盖公共无效配置(WebSecurity web)抛出异常{网络.忽略().antMatchers("/static/**");}}

  • 声明一个 WebMvcConfigurer

    @EnableWebMvc@配置@ComponentScan(basePackages = {"com.app.controller","com.app.service",com.app.dao"})公共类 WebMvcConfigurer 扩展了 WebMvcConfigurerAdapter {@豆角,扁豆公共 ViewResolver viewResolver() {InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();viewResolver.setPrefix("/WEB-INF/view/");viewResolver.setSuffix(".jsp");返回视图解析器;}@覆盖public void addViewControllers(ViewControllerRegistry 注册表) {registry.addViewController("/page").setViewName("page");}@覆盖public void addResourceHandlers(ResourceHandlerRegistry registry) {registry.addResourceHandler("static/**").addResourceLocations("static/");}}

  • 声明一个安全初始化器

    公共类 SecurityWebAppInitializer扩展 AbstractSecurityWebApplicationInitializer { }

  • 声明一个应用初始化器

    public class Initializer extends AbstractAnnotationConfigDispatcherServletInitializer {@覆盖受保护的类[] getRootConfigClasses() {返回新类[]{WebSecurityConfigurer.class};}@覆盖受保护的类[] getServletConfigClasses() {返回新类[]{WebMvcConfigurer.class, DataSourceConfigurer.class};}@覆盖受保护的字符串[] getServletMappings() {返回新字符串[]{"/"};}}

  • 实现您的自定义身份验证提供程序

    @Component@ComponentScan(basePackages = {"com.app.service"})公共类 CustomAuthenticationProvider 实现 AuthenticationProvider {私有静态最终记录器日志 = LoggerFactory.getLogger(CustomAuthenticationProvider.class);@注入私有 AppService 服务;@覆盖公共身份验证身份验证(身份验证身份验证)抛出 AuthenticationException {//Thread.dumpStack();字符串用户名 = authentication.getName();字符串密码 = authentication.getCredentials().toString();String message = String.format("用户名:'%s'密码:'%s'",用户名,密码);UserBean userBean = service.validate(username, password);日志调试(消息);如果(用户豆!= null){列表grantAuths = new ArrayList<>();grantAuths.add(new SimpleGrantedAuthority("USER"));return new UsernamePasswordAuthenticationToken(userBean, authentication, grantAuths);} 别的 {String error = String.format("无效凭据 [%s]", message);抛出新的 BadCredentialsException(error);}}@覆盖公共布尔支持(类身份验证){返回 authentication.equals(UsernamePasswordAuthenticationToken.class);}}

  • 我将跳过 EchoController、AppService、AppDao 和 UserBean.

    谢谢.

    解决方案

    在 3.2 版本中,post 参数已从 j_username 更改为 username 和 j_password 更改为密码.登录 url 也从/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

    1. Create a login page

      <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
      <!DOCTYPE html>
      <html>
          <head>
              <meta charset="ISO-8859-1">
              <title>Test</title>
              <script src="static/js/jquery-1.10.2.min.js"></script>
              <script src="static/js/app-controller.js"></script>
          </head>
          <body>
              <div>Login</div>
              <form name="f" action="<c:url value="/j_spring_security_check"/>" method="POST">
                  <label for="password">Username</label>&nbsp;<input type="text" id="j_username" name="j_username"><br/>
                  <label for="password">Password</label>&nbsp;<input type="password" id="j_password" name="j_password"><br/>
                  <input type="submit" value="Validate">&nbsp;<input name="reset" type="reset">
                  <input type="hidden" id="${_csrf.parameterName}" name="${_csrf.parameterName}" value="${_csrf.token}"/>
              </form>
              <hr/>
              <c:if test="${param.error != null}">
                  <div>
                      Failed to login.
                      <c:if test="${SPRING_SECURITY_LAST_EXCEPTION != null}">
                        Reason: <c:out value="${SPRING_SECURITY_LAST_EXCEPTION.message}" />
                      </c:if>
                  </div>
              </c:if>
              <hr/>
              <input type="button" value="Echo" id="echo" name="echo" onclick="AppController.echo();">
              <div id="echoContainer"></div>
      
          </body>
      </html>
      

    2. Declare a WebSecurityConfigurer HERE IS WHERE I WAS MISSING j_username AND 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. Declare a 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/");
          }
      
      }
      

    4. Declare a Security Initializer

      public class SecurityWebAppInitializer 
          extends AbstractSecurityWebApplicationInitializer { }
      

    5. Declare an App Initialzer

      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[]{"/"};
          }
      
      }
      

    6. Implement your custom Authentication Provider

      @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);
          }
      
      }
      

    I am skipping EchoController, AppService, AppDao and UserBean.

    Thanks.

    解决方案

    In 3.2 version post parameters have changed from j_username to username and j_password to password. The login url has also changed from /j_spring_security_check to /login.

    See this link for the explanation of why this change was implemented: http://docs.spring.io/spring-security/site/docs/3.2.0.RELEASE/reference/htmlsingle/#jc-httpsecurity. These are the changes:

    • GET /login renders the login page instead of /spring_security_login

    • POST /login authenticates the user instead of /j_spring_security_check

    • The username parameter defaults to username instead of j_username

    • The password parameter defaults to password instead of j_password

    And this for an example of a login form: http://docs.spring.io/spring-security/site/docs/3.2.0.RELEASE/reference/htmlsingle/#jc-form

    这篇关于JavaConfiguration for Spring 4.0 + Security 3.2 + j_spring_security_check的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆