如何将spring security xml转换为注释

时间:2016-08-19 09:40:29

标签: spring spring-mvc spring-security

我有一个应用程序使用spring security configure xml与spring MVC集成。

我的spring security配置xml:

<http pattern="/admin/**" authentication-manager-ref="adminAuthenticationManager">
    <intercept-url pattern="/" access="permitAll" />
    <form-login login-page="/login" username-parameter="userEmail"
        login-processing-url="/admin/j_spring_security_check"
        authentication-success-handler-ref="customAuthenticationSuccessHandler"
        password-parameter="password" authentication-failure-url="/admin/login?error" />
    <logout logout-url="/admin/j_spring_security_logout"
        logout-success-url="/admin/login?logout" />
    <remember-me key="uniqueAndSecret" user-service-ref="customUserDetailsService"
        token-validity-seconds="7776000" />
    <csrf disabled="true" />
</http>
<http authentication-manager-ref="userAuthenticationManager">
    <intercept-url pattern="/" access="permitAll" />
    <form-login login-page="/login" username-parameter="userEmail"
        login-processing-url="/j_spring_security_check" password-parameter="password"
        authentication-success-handler-ref="customAuthenticationSuccessHandler"
        authentication-failure-url="/login?error" />
    <logout logout-url="/j_spring_security_logout"
        logout-success-url="/login?logout" />
    <remember-me key="uniqueAndSecret" user-service-ref="customAdminDetailsService"
        token-validity-seconds="7776000" />
    <csrf disabled="true" />
</http>

<authentication-manager erase-credentials="false"
    id="userAuthenticationManager">
    <authentication-provider user-service-ref="customUserDetailsService" />
</authentication-manager>
<authentication-manager erase-credentials="false"
    id="adminAuthenticationManager">
    <authentication-provider user-service-ref="customAdminDetailsService" />
</authentication-manager>

<beans:bean id="customUserDetailsService"
    class="com.service.impl.UserDetailServiceImpl" />
<beans:bean id="customAdminDetailsService"
    class="com.service.impl.AdminDetailServiceImpl" />

我的自定义UserServiceDetailImpl文件:

@Service 
public class UserDetailServiceImpl implements UserDetailsService {
@Autowired
private UserService userService;

@Override
public UserDetails loadUserByUsername(String email) {
    try {
        User user = userService.getUserByEmail(email);
        if (user != null) {
            return new org.springframework.security.core.userdetails.User(user.getUserEmail(), user.getPassword(),
                    true, true, true, true, getGrantedAuthorities(user));
        } else {
            throw new UsernameNotFoundException(email);
        }
    } catch (Exception e) {
        throw new UsernameNotFoundException(email);
    }
}

private List<GrantedAuthority> getGrantedAuthorities(Object generalUser) {
    List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
    if (generalUser instanceof User) {
        authorities.add(new SimpleGrantedAuthority(CommonConstant.Role.USER.toString()));
    }
    return authorities;
    }
}

现在如何通过注释将其更改为弹簧配置?

当我更改为在spring security中使用注释时,我的WebsercurityConfig文件:

@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

@Autowired
UserDetailServiceImpl userDetailService;

@Autowired
AdminDetailServiceImpl adminDetailService;

@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
    auth.userDetailsService(userDetailService);
    auth.userDetailsService(adminDetailService);
}

@Override
protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests().antMatchers("/").permitAll()
            .and().formLogin().loginPage("/login")
            .failureUrl("/login?error").loginProcessingUrl("/j_spring_security_check")
            .successHandler(loginSuccessHanlder).failureUrl("/login?error=true")
            .usernameParameter("userEmail").passwordParameter("password")
            .and().logout().logoutUrl("/j_spring_security_logout").logoutSuccessUrl("/login?logout")
            .and().userDetailsService(userDetailService)
            .rememberMe().key("uniqueAndSecret")
            .tokenValiditySeconds(33343)
            .and()
            .authorizeRequests().antMatchers("/admin/**").permitAll()
            .and().formLogin().loginPage("/login")
            .failureUrl("/admin/login?error").loginProcessingUrl("/admin/j_spring_security_check")
            .successHandler(loginSuccessHanlder).failureUrl("/admin/login?error=true")
            .usernameParameter("userEmail").passwordParameter("password")
            .and().logout().logoutUrl("/admin/j_spring_security_logout").logoutSuccessUrl("/admin/login?logout")
            .and().userDetailsService(userDetailService)
            .rememberMe().key("uniqueAndSecret")
            .tokenValiditySeconds(33343);
     }
}

1 个答案:

答案 0 :(得分:1)

Documentation应该帮助你

@Configuration
@EnableWebSecurity
public class SecurityConfig {

@Autowired
private UserDetailServiceImpl userDetailService;

 @Autowired
 public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
  auth.userDetailsService(userDetailService)
  auth.userDetailsService(customAdminDetailsService());
 }



 @Bean
 UserDetailsService customAdminDetailsService() {
  /* custom UserDetailsService code here */
 }


 @Override
 protected void configure(HttpSecurity http) throws Exception {
  http.antMatchers("/").permitAll()
   .and()
   .formLogin().loginPage("/login").failureUrl("/login?error")
   .createLoginProcessingUrlMatcher("/j_spring_security_check")
   .successHandler(customAuthenticationSuccessHandler()).failureUrl("/login?error").usernameParameter("userEmail").passwordParameter("password").logout().invalidateHttpSession(false)
   .logoutUrl("/custom-logout").logoutSuccessUrl("/logout-success")
   .userDetailsService(customUserDetailsService()).rememberMe().key("uniqueAndSecret").userDetailsService(customUserDetailsService()).tokenValiditySeconds(33343)
   .csrf().disable()
   .and()
   .antMatcher("/admin/**")

  /*  your admin configurations  */

 }

}