Spring Security java配置和数据库似乎不起作用

时间:2016-04-26 06:58:43

标签: java spring spring-mvc spring-security spring-data-jpa

我想使用Spring Security和数据库来登录我的应用程序中的注销用户

patterns

我的secutity配置如下

<form action="${pageContext.request.contextPath}/login/authenticate" method="post">

  <input class="md-input" type="text" id="login_email" name="username" />
  <input class="md-input" type="password" id="login_password" name="password" />  
  <input type="submit" class="md-btn md-btn-primary md-btn-block md-btn-large" value="Sign In">           

  <c:if test="${param.error ne null}">
    <div class="alert-danger">Invalid username and password.</div>
  </c:if>
  <c:if test="${param.logout ne null}">
    <div class="alert-normal">You have been logged out.</div>
  </c:if>
  <input type="hidden" name="${_csrf.parameterName}" value="${_csrf.token}" />

</form>

和CustomUserDetails

@Configuration
@EnableWebSecurity
public class WebSecurityContextConfigurer extends WebSecurityConfigurerAdapter{

    @Autowired 
     private UserDetailsService userDetailsService;

     @Autowired
     public void configAuthentication(AuthenticationManagerBuilder auth) throws Exception {    
         auth.userDetailsService(userDetailsService).passwordEncoder(passwordencoder());
     } 

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

    @Override
    protected void configure(HttpSecurity http) throws Exception {
          http
          //Configures form login
          .formLogin()
              .loginPage("/login")
              .loginProcessingUrl("/login/authenticate")
              .failureUrl("/login?error=bad_credentials")
          //Configures the logout function
          .and()
              .logout()
                  .deleteCookies("JSESSIONID")
                  .logoutUrl("/logout")
                  .logoutSuccessUrl("/")
          //Configures url based authorization
          .and()
              .authorizeRequests()
                  //Anyone can access the urls
                  .antMatchers(
                          "/auth/**",
                          "/",
                  ).permitAll()
                  //The rest of the our application is protected.
                  .antMatchers("/**").hasRole("USER");
    }


    @Bean(name="passwordEncoder")
    public PasswordEncoder passwordencoder(){
     return new BCryptPasswordEncoder();
    }

}

和CustomUserDetailsS​​ervice是

public class CustomUserDetails extends User implements UserDetails {    

    private static final long serialVersionUID = 1L;
    private List<String> userRoles;


    public CustomUserDetails(User user){
        super(user);

    }


    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {

        String roles=StringUtils.collectionToCommaDelimitedString(userRoles);           
        return AuthorityUtils.commaSeparatedStringToAuthorityList(roles);
    }

    @Override
    public boolean isAccountNonExpired() {
        // TODO Auto-generated method stub
        return true;
    }
    @Override
    public boolean isAccountNonLocked() {
        return true;
    }

    @Override
    public boolean isCredentialsNonExpired() {
        return true;
    }
    @Override
    public boolean isEnabled() {
        return true;
    }


    @Override
    public String getUsername() {
        return super.getUserName();
    }


    @Override
    public String getPassword() {
        // TODO Auto-generated method stub
        return null;
    }


}

和AppInitializer是

@Service("customUserDetailsService")
public class CustomUserDetailsService implements UserDetailsService{
    private final UserService userService;


    @Autowired
    public CustomUserDetailsService(UserService userService) {
        this.userService = userService;
        //this.userRolesRepository=userRolesRepository;
    }


    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        User user=userService.findByEmail(username);
        if(null == user){
            throw new UsernameNotFoundException("No user present with username: "+username);
        }else{

            return new CustomUserDetails(user);
        }
    }

}

最后我的映射是

public class WebAppInitializer implements WebApplicationInitializer {

    public void onStartup(ServletContext servletContext) throws ServletException {  

        WebApplicationContext rootContext = getWebApplicationContext();
        servletContext.addListener(new ContextLoaderListener(rootContext)); 

        // add the dispatcher servlet and map it to /
        DispatcherServlet dispatcherServlet = new DispatcherServlet(rootContext);
        dispatcherServlet.setThrowExceptionIfNoHandlerFound(true);
        ServletRegistration.Dynamic dispatcher = servletContext.addServlet(
                "springDispatcher", dispatcherServlet);
        dispatcher.setAsyncSupported(true);
        dispatcher.setLoadOnStartup(0);
        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, "/*");


    }

    private AnnotationConfigWebApplicationContext getWebApplicationContext() {
        AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext();
        context.setConfigLocation("pkj.to.files.of.config");
        return context;
    }

}

当我每次尝试登录到应用程序时,我都会重新登录到登录页面并且登录不起作用

0 个答案:

没有答案