账号密码登录
微信安全登录
微信扫描二维码登录

登录后绑定QQ、微信即可实现信息互通

手机验证码登录
找回密码返回
邮箱找回 手机找回
注册账号返回
其他登录方式
分享
  • 收藏
    X
    SpringSecurity如何存储用户信息?
    45
    0

    如题,SpringSecurity是如何存储用户信息的?怎么存储才能保证每一个登录用户所获取到的UserDetails是自己对应的。

    UserDetails userDetails = (UserDetails) SecurityContextHolder.getContext() .getAuthentication() .getPrincipal();
    是怎么直接获取到当前登录用户的? 是通过什么判断是否是当前用户的?他们是通过什么来做一对一的关系的?求大佬指点~

    0
    打赏
    收藏
    点击回答
        全部回答
    • 0
    • 全是好儿郎 普通会员 1楼

      Spring Security可以使用多种方式存储用户信息,具体取决于你的需求和你正在使用的数据库类型。

      1. MySQL数据库:

      Spring Security支持MySQL数据库存储用户信息。你可以使用MySQL的用户表(user)来存储用户信息,该表包含用户名(username)、密码(password)、电子邮件地址(email)等字段。

      以下是一个简单的示例:

      ```java @Configuration public class SecurityConfig extends WebSecurityConfigurerAdapter {

      @Override
      protected void configure(HttpSecurity http) throws Exception {
          http.authorizeRequests()
                  .antMatchers("/").permitAll()
                  .anyRequest().authenticated()
                  .and()
                  .formLogin().loginPage("/login").permitAll()
                  .and()
                  .logout().permitAll();
      }
      

      } ```

      在这个示例中,我们设置了允许所有路由的访问权限。我们还添加了一个formLogin中间件,用于在用户未登录时显示登录页面。

      1. PostgreSQL数据库:

      Spring Security也可以使用PostgreSQL数据库存储用户信息。你可以使用PostgreSQL的用户表(user)来存储用户信息,该表包含用户名(username)、密码(password)、电子邮件地址(email)等字段。

      以下是一个简单的示例:

      ```java @Configuration public class SecurityConfig extends WebSecurityConfigurerAdapter {

      @Override
      protected void configure(HttpSecurity http) throws Exception {
          http.authorizeRequests()
                  .antMatchers("/").permitAll()
                  .anyRequest().authenticated()
                  .and()
                  .formLogin().loginPage("/login").permitAll()
                  .and()
                  .logout().permitAll();
      }
      

      } ```

      在这个示例中,我们设置了允许所有路由的访问权限。我们还添加了一个formLogin中间件,用于在用户未登录时显示登录页面。

      1. MongoDB数据库:

      Spring Security也可以使用MongoDB数据库存储用户信息。你可以使用MongoDB的用户表(user)来存储用户信息,该表包含用户名(username)、密码(password)、电子邮件地址(email)等字段。

      以下是一个简单的示例:

      ```java @Configuration public class SecurityConfig extends WebSecurityConfigurerAdapter {

      @Override
      protected void configure(HttpSecurity http) throws Exception {
          http.authorizeRequests()
                  .antMatchers("/").permitAll()
                  .anyRequest().authenticated()
                  .and()
                  .formLogin().loginPage("/login").permitAll()
                  .and()
                  .logout().permitAll();
      }
      

      } ```

      在这个示例中,我们设置了允许所有路由的访问权限。我们还添加了一个formLogin中间件,用于在用户未登录时显示登录页面。

      请注意,你需要将数据库的URL和表名替换为你自己的值。

    更多回答
    扫一扫访问手机版
    • 回到顶部
    • 回到顶部