一般的身份认证
从Spring Security核心部分,对Spring Security有一个笼统概念了,那该怎么理解上面说的呢?
通常情况下,我们的系统都是这样的:
1、用户输入用户名、密码登录
2、系统对用户名、密码进行验证
3、获取用户上下文信息(角色列表等等)
4、获取相关操作权限
对于上面说的前三条,用Spring Security来处理,就是:
1、用户名、密码组合生成一个Authentication对象(也就是UsernamePasswordAuthenticationToken对象)。
2、生成的这个token对象会传递给一个AuthenticationManager对象用于验证。
3、当成功认证后,AuthenticationManager返回一个Authentication对象。
4、接下来,就可以调用
SecurityContextHodler.getContext().setAuthentication(…)。
为了更好的理解,下面就写一个例子:
package com.springsecurity.java.test; import java.io.BufferedReader; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.List; import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.authentication.BadCredentialsException; 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.authority.SimpleGrantedAuthority; import org.springframework.security.core.context.SecurityContextHolder; public class AuthenticationExample { private static SimpleAuthenticationManager samgr = new SimpleAuthenticationManager(); public static void main(String[] args) { try { // 用户输入用户名、密码: BufferedReader in = new BufferedReader(new InputStreamReader( System.in)); System.out.println("Please enter your username:"); String name = in.readLine(); System.out.println("Please enter your password:"); String password = in.readLine(); // 接下来是系统进行身份认证的过程: //1、将用户名、密码封装成一个token Authentication token = new UsernamePasswordAuthenticationToken( name, password); //2、将token传给AuthenticationManager进行身份认证 //3、认证完毕,返回一个认证后的身份: Authentication result = samgr.authenticate(token); // 认证后,存储到SecurityContext里 : SecurityContextHolder.getContext().setAuthentication(result); } catch (Exception ex) { System.out.println("认证失败"); } // 从SecurityContext读取认证的身份: System.out.println(SecurityContextHolder.getContext() .getAuthentication()); } } class SimpleAuthenticationManager implements AuthenticationManager { static final List<GrantedAuthority> AUTHORITIES = new ArrayList<GrantedAuthority>(); static { AUTHORITIES.add(new SimpleGrantedAuthority("ROLE_USER")); } public Authentication authenticate(Authentication auth) throws AuthenticationException { if (auth.getName().equals(auth.getCredentials())) { return new UsernamePasswordAuthenticationToken(auth.getName(), auth.getCredentials(),AUTHORITIES); } throw new BadCredentialsException("Bad Credentials"); } }