# Spring Security 自动登录

Spring Security 怎么判断一个用户是否登录了呢？

• MyUserDetails.java
• MyUserDetailsService.java
• MyAuthenticationProvider.java
• SecurityUtils.java
• UserDao.java
• spring-security.xml

## MyUserDetailsService.java

The UserDetailsService

Another item to note from the above code fragment is that you can obtain a principal from the Authentication object. The principal is just an Object. Most of the time this can be cast into a UserDetails object. UserDetails is a central interface in Spring Security. It represents a principal, but in an extensible and application-specific way. Think of UserDetails as the adapter between your own user database and what Spring Security needs inside the SecurityContextHolder. Being a representation of something from your own user database, quite often you will cast the UserDetails to the original object that your application provided, so you can call business-specific methods (like getEmail(), getEmployeeNumber() and so on).

By now you’re probably wondering, so when do I provide a UserDetails object? How do I do that? I thought you said this thing was declarative and I didn’t need to write any Java code - what gives? The short answer is that there is a special interface called UserDetailsService. The only method on this interface accepts a String-based username argument and returns a UserDetails:

This is the most common approach to loading information for a user within Spring Security and you will see it used throughout the framework whenever information on a user is required.

On successful authentication, UserDetails is used to build the Authentication object that is stored in the SecurityContextHolder (more on this below). The good news is that we provide a number of UserDetailsService implementations, including one that uses an in-memory map (InMemoryDaoImpl) and another that uses JDBC (JdbcDaoImpl). Most users tend to write their own, though, with their implementations often simply sitting on top of an existing Data Access Object (DAO) that represents their employees, customers, or other users of the application. Remember the advantage that whatever your UserDetailsService returns can always be obtained from the SecurityContextHolder using the above code fragment.

## MyAuthenticationProvider.java

MyAuthenticationProvider 提供了登陆的逻辑。

## SecurityUtils.java

SecurityUtils 提供了登陆的接口 login()，还有一些和登陆有关的方法。

## 测试

4. 点击 QQ 绑定用户自动登陆，登陆成功后重定向到 Admin 页面
6. 点击，Admin 登陆，登陆成功后重定向到 Admin 页面
8. 点击 不存在用户登陆，提示登陆失败