Spring Security使用
Spring Security使用
yan5845hao 发表于7个月前
Spring Security使用
  • 发表于 7个月前
  • 阅读 24
  • 收藏 0
  • 点赞 0
  • 评论 0

腾讯云 技术升级10大核心产品年终让利>>>   

重写WebSecurityConfigurerAdapter

package com.uwo.security.roles.configuration;
import com.uwo.security.roles.provider.UwoAuthenticationProvider;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
/**
 * Created by yanhao on 2017/5/24.
 */
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class UwoSecurity extends WebSecurityConfigurerAdapter {
    // 自定义验证
    @Autowired
    private UwoAuthenticationProvider authenticationProvider;
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.authenticationProvider(authenticationProvider);
    }
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                .antMatchers("/css/**", "/img/**").permitAll()
                .antMatchers("/login").permitAll()
                .anyRequest().authenticated()
            .and()
                .formLogin()
                    .loginPage("/login")
                    .failureUrl("/login?error")
                    .defaultSuccessUrl("/")
                .permitAll()
            .and()
                .logout().permitAll();
    }
}

HttpSecurity使用

  • http过滤
http.addFilter(实现Filter.class)
http.addFilterBefore(实现Filter.class)  
http.addFilterAfter(实现Filter.class)  
  • ExpressionInterceptUrlRegistry配置 (http.authorizeRequests())
// 配置
http.authorizeRequests()
    .antMatchers("无需授权").permitAll()
    // 剩下的请求都需要授权请求
    .anyRequest().authenticated()
  • FormLoginConfigurer 配置(http.formLogin())
// 配置
http.formLogin()
    .loginProcessingUrl("默认自带的登录页面地址")
    .loginPage("控制器路由登录地址")
    .usernameParameter("用户名参数")
    .passwordParameter("密码参数")
    .defaultSuccessUrl("默认成功地址")
    .failureUrl("失败地址")
    .failureForwardUrl("失败跳转地址")
    .failureHandler(实现AuthenticationFailureHandler.class)
    .successHandler(实现AuthenticationSuccessHandler.class)

AuthenticationManagerBuilder使用

// 设置固定权限
auth.inMemoryAuthentication()
                .withUser("user").password("password").roles("USER");
// 获取用户信息
auth.userDetailsService(实现UserDetailsService.class)
    // 设置加密算法与密码匹配
      .passwordEncoder(实现PasswordEncoder.class)
// 上面的众合体
auth.authenticationProvider(实现AuthenticationProvider.class)

UserDetailsService实现

package com.uwo.security.roles.service;
import com.uwo.security.roles.pojo.Uwo;
import org.apache.log4j.Logger;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
/**
 * Created by yanhao on 2017/5/24.
 */
@Service
public class UwoService implements UserDetailsService {
    private final Logger log = Logger.getLogger(UwoService.class);
    public UserDetails loadUserByUsername(String user) throws UsernameNotFoundException {
        log.warn("username = " + user);
        Uwo uwo = new Uwo();
        uwo.setUsername("uwo");
        uwo.setPassword("123456");
        uwo.setRole("ADMIN");
        return uwo;
    }
}

AuthenticationProvider实现

package com.uwo.security.roles.provider;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.stereotype.Component;
import java.util.Collection;
/**
 * Created by yanhao on 2017/5/25.
 */
@Component
public class UwoAuthenticationProvider implements AuthenticationProvider {
    private final Logger log = Logger.getLogger(UwoAuthenticationProvider.class);
    @Autowired
    private UserDetailsService userDetailsService;
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        String username = authentication.getName();
        String password = (String) authentication.getCredentials();
        log.warn("username == " + username + "password == " + password);
        /// 用户名验证实施代码
        UserDetails user = userDetailsService.loadUserByUsername(username);
        /// 用户验证实施代码
        /// 密码加密实施代码
        Collection<? extends GrantedAuthority> authorities = user.getAuthorities();
        return new UsernamePasswordAuthenticationToken(user, password, authorities);
    }
    public boolean supports(Class<?> aClass) {
        return true;
    }
}

PasswordEncoder实现

package com.uwo.security.roles.provider;
import org.apache.log4j.Logger;
import org.springframework.security.crypto.password.PasswordEncoder;
/**
 * Created by yanhao on 2017/5/25.
 */
public class UwoPasswordEncoder implements PasswordEncoder {
    private final Logger log = Logger.getLogger(UwoPasswordEncoder.class);
    /**
     * 密码加密
     * @param password
     * @return
     */
    public String encode(CharSequence password) {
        log.warn("password == " + password);
        return password.toString();
    }
    /**
     * 密码验证
     * @param password
     * @param encodedPassword
     * @return
     */
    public boolean matches(CharSequence password, String encodedPassword) {
        log.warn("password == " + password + " -=- encodedPassword == " + encodedPassword);
        return encodedPassword.equals(password.toString());
    }
}
共有 人打赏支持
粉丝 7
博文 102
码字总数 20648
×
yan5845hao
如果觉得我的文章对您有用,请随意打赏。您的支持将鼓励我继续创作!
* 金额(元)
¥1 ¥5 ¥10 ¥20 其他金额
打赏人
留言
* 支付类型
微信扫码支付
打赏金额:
已支付成功
打赏金额: