Spring Security应用

Spring Security 基于 Spring 框架,提供了一套 Web 应用安全性的完整解决方案。一般来说,Web 应用的安全性包括用户认证(Authentication)和用户授权(Authorization)两个部分。用户认证指的是验证某个用户是否为系统中的合法主体,也就是说用户能否访问该系统。用户认证一般要求用户提供用户名和密码。系统通过校验用户名和密码来完成认证过程。用户授权指的是验证某个用户是否有权限执行某个操作。在一个系统中,不同用户所具有的权限是不同的。比如对一个文件来说,有的用户只能进行读取,而有的用户可以进行修改。一般来说,系统会为不同的用户分配不同的角色,而每个角色则对应一系列的权限。

对于上面提到的两种应用情景,Spring Security 框架都有很好的支持。在用户认证方面,Spring Security 框架支持主流的认证方式,包括 HTTP 基本认证、HTTP 表单验证、HTTP 摘要认证、OpenID 和 LDAP 等。在用户授权方面,Spring Security 提供了基于角色的访问控制和访问控制列表(Access Control List,ACL),可以对应用中的领域对象进行细粒度的控制。
参考:https://blog.csdn.net/xlecho/article/details/80026527?utm_source=copy

核心接口UserDetailService

public interface UserDetailsService {
    UserDetails loadUserByUsername(String var1) throws UsernameNotFoundException;
}

自定义MyUserService实现UserDetailsService,重写loadUserByUsername方法

public MyUserService implements UserDetailsService{
    @Override
    public UserDetails loadUserByUsername(String username) {
        RentAgentUser agent  =  new RentAgentUser();
        agent.setUsername("agent01");
        agent.setPassword("123456);
        String role = "admin";    // 从数据库读取相应角色
        return new CurrentUser(agent,role);
    }
}

UserDetails类封装了用户信息的对象,里面包含了七个方法

public interface UserDetails extends Serializable {
    // 封装了权限信息
    Collection<? extends GrantedAuthority> getAuthorities();
    // 密码信息
    String getPassword();
    // 登录用户名
    String getUsername();
    // 帐户是否过期
    boolean isAccountNonExpired();
    // 帐户是否被冻结
    boolean isAccountNonLocked();
    // 帐户密码是否过期,一般有的密码要求性高的系统会使用到,比较每隔一段时间就要求用户重置密码
    boolean isCredentialsNonExpired();
    // 帐号是否可用
    boolean isEnabled();
}

---------------------

本文来自 whyalwaysmea 的CSDN 博客 ,全文地址请点击:https://blog.csdn.net/u013435893/article/details/79596628?utm_source=copy 

public class CurrentUser extends User {
  private static final long serialVersionUID = -5094740218770314002L;

  private CurrentUser(String username, String password, boolean enabled, boolean accountNonExpired,
                     boolean credentialsNonExpired, boolean accountNonLocked,
                     Collection<? extends GrantedAuthority> authorities) {
    super(username, password, enabled, accountNonExpired,
        credentialsNonExpired, accountNonLocked, authorities);
  }

  public CurrentUser(PubUser user) {
    this(user.getUserId(), user.getPassword(), true, true, true,
        true, AuthorityUtils.commaSeparatedStringToAuthorityList("ROLE_USER,ROLE_ADMIN,USER"));
  }

  public CurrentUser(PubUser user, String role) {
    this(user.getUserId(), user.getPassword(), true, true, true,
        true, AuthorityUtils.commaSeparatedStringToAuthorityList(role));
  }

  public CurrentUser(RentAgentUser user) {
    this(user.getUserId(), user.getPassword(), true, true, true,
        true, AuthorityUtils.commaSeparatedStringToAuthorityList("ROLE_USER,ROLE_AGENT"));
  }

  public CurrentUser(RentAgentUser user, String role) {
    this(user.getUserId(), user.getPassword(), true, true, true,
        true, AuthorityUtils.commaSeparatedStringToAuthorityList(role));
  }

代码中的User类为spring为我们提供的类,该类实现了UserDetails和credentialsContainer 两个接口。

自定义RentAgentUser类

@Data
public class RentAgentUser implements Serializable {
    private static final long serialVersionUID = 1L;
    private String agentId;
    private String username;
    private String password;
  }

WebSerurityConfigurerAdapter类用于配置用户权限,接受一个HttpSecurity类型参数http,configure方法用于定义安全策略

@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
  private static final String ADMIN = "ROLE_ADMIN";
  private static final String FRONT = "ROLE_FRONT";
  private static final String AGENT = "ROLE_AGENT";

  @Override
  protected void configure(HttpSecurity http) throws Exception {
    http.authorizeRequests()
        .antMatchers("/home").authenticated()
        .antMatchers("/user/**").authenticated()
        .antMatchers("/stock/**").hasAuthority(ADMIN)
        .antMatchers("/admin/**").hasAuthority(ADMIN)
        .antMatchers("/niufi/**").hasAuthority(ADMIN)
        .antMatchers("/manage/order/view", "/manage/order/delivery/view")  
        .hasAnyAuthority(ADMIN, "QUERY_ORDER")
        .antMatchers("/erp/**").hasAnyAuthority(ADMIN, "ERP_FRONT")  // erp前台
        .and().formLogin().loginPage("/login").failureUrl("/login?error")
        .and().exceptionHandling().accessDeniedPage("/accessdenied").and().logout()
        .logoutUrl("/logout").logoutSuccessUrl("/login").invalidateHttpSession(true)
        .permitAll().and().csrf().disable();
  }
}

前端页面配置

引入xmlns:sec=“http://www.thymeleaf.org/thymeleaf-extras-springsecurity3
在li标签内添加属性sec:authorize=“ADMIN”即可实现基于角色的访问控制,没有该权限的用户页面将不显示该li标签。

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org"
      xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity3">
      <head lang="en" th:fragment="head">
	<meta name="toTop" content="true" />
	<meta http-equiv="X-UA-Compatible" content="IE=edge" />
	<meta http-equiv="Content-Type" content="textml; charset=UTF-8" />
    <title th:text="#{app.name}">EMCAD(ON)</title>
</head>
<body>
	<ul>
		<li sec:authorize="hasAuthority('ROLE_ADMIN')"></li>
		<li sec:authorize="hasAuthority('CREATE_ORDER')"></li>
	</url>
</body>
</html>

猜你喜欢

转载自blog.csdn.net/zhouhaihua57410/article/details/82822634