81,092
社区成员
发帖
与我相关
我的任务
分享
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");
}
}