Spring Security 之身份认证

Spring Security可以运行在不同的身份认证环境中,当我们推荐用户使用Spring Security进行身份认证但并不推荐集成到容器管理的身份认证中时,但当你集成到自己的身份认证系统时,它依然是支持的。

1. Spring Security中的身份认证是什么?

现在让我们考虑一下每个人都熟悉的标准身份认证场景:

(1)用户打算使用用户名和密码登陆系统

(2)系统验证用户名和密码合法

(3)得到用户信息的上下文(角色等信息)

(4)为用户建立一个安全上下文

(5)用户接下来可能执行一些权限访问机制下的受保护的操作,检查与当前安全上下文有关的必须的权限

上面前三步是身份认证的过程,接下来看看身份认证的详细过程:

(1)用户名和密码获得之后组合成UsernamePasswordAuthenticationToken的实例(前文讨论过的Authentication接口的实例)

(2)将该令牌传递给AuthenticationManager实例进行验证

(3)验证成功后,AuthenticationManager 会返回填充好的Authentication实例

(4)通过调用SecurityContextHolder.getContext().setAuthentication(…)建立安全上下文的实例,传递到返回的身份认证对象上

下面是进行身份认证的代码片段:

importorg.springframework.security.authentication.*;importorg.springframework.security.core.*;importorg.springframework.security.core.authority.SimpleGrantedAuthority;importorg.springframework.security.core.context.SecurityContextHolder;publicclassAuthenticationExample{privatestaticAuthenticationManageram=newSampleAuthenticationManager();publicstaticvoidmain(String[]args)throwsException{BufferedReaderin=newBufferedReader(newInputStreamReader(System.in));while(true){System.out.println(“Pleaseenteryourusername:”);Stringname=in.readLine();System.out.println(“Pleaseenteryourpassword:”);Stringpassword=in.readLine();try{Authenticationrequest=newUsernamePasswordAuthenticationToken(name,password);Authenticationresult=am.authenticate(request);SecurityContextHolder.getContext().setAuthentication(result);break;}catch(AuthenticationExceptione){System.out.println(“Authenticationfailed:”+e.getMessage());}}System.out.println(“Successfullyauthenticated.Securitycontextcontains:”+SecurityContextHolder.getContext().getAuthentication());}}classSampleAuthenticationManagerimplementsAuthenticationManager{staticfinalList<GrantedAuthority>AUTHORITIES=newArrayList<GrantedAuthority>();static{AUTHORITIES.add(newSimpleGrantedAuthority(“ROLE_USER”));}publicAuthenticationauthenticate(Authenticationauth)throwsAuthenticationException{if(auth.getName().equals(auth.getCredentials())){returnnewUsernamePasswordAuthenticationToken(auth.getName(),auth.getCredentials(),AUTHORITIES);}thrownewBadCredentialsException(“BadCredentials”);}}

我们写了一个小程序,要求用户输入用户名和密码并执行上述序列。我们实现的 AuthenticationManager 会验证用户名和密码是否一致,它分配了一个角色给每个用户。上面的输出类似于这样:

Please enter your username:

favboy

Please enter your password:

favccxx

Authentication failed:Bad Credentials

Please enter your username:

favboy

Please enter your password:

favboy

Successfully authenticated. Security context contains: \

org.springframework.security.authentication.UsernamePasswordAuthenticationToken@441d0230: \

Principal: bob; Password: [PROTECTED]; \

Authenticated: true; Details: null; \

Granted Authorities: ROLE_USER

听他第二十八次提起童年往事,每年的同一天和他庆祝生日,

Spring Security 之身份认证

相关文章:

你感兴趣的文章:

标签云: