【问题标题】:Spring Boot - using inMemoryAuthenticationSpring Boot - 使用 inMemoryAuthentication
【发布时间】:2018-05-06 04:15:59
【问题描述】:

我使用 Spring Initializer、嵌入式 Tomcat、Thymeleaf 模板引擎生成了一个 Spring Boot Web 应用程序,并将其打包为可执行 JAR 文件。

使用的技术:

Spring Boot 2.0.0.M6,Java 8,maven

我有这个安全配置文件,以便在开发阶段用于内存身份验证

在我的应用程序中。我有一个用户域对象:

import org.springframework.security.core.userdetails.UserDetails;
public class User implements Serializable, UserDetails {
..
}

在我的安全配置类中

@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
        auth
                .inMemoryAuthentication()
                .withUser(User
                        .withDefaultPasswordEncoder()
                        .username(DEV_USER)
                        .password(DEV_PWD)
                        .roles("ADMIN").build());
    }

但是当我从 SecurityContextHolder 获取用户时:

 SecurityContextHolder.getContext().
                getAuthentication().getPrincipal()

我遇到了一个错误:

org.springframework.security.core.userdetails.User cannot be cast to com.iberia.domain.backend.User

但我找不到构造 UserDetails 对象的方法:

UserDetails
                            .withDefaultPasswordEncoder()
                            .username(DEV_USER)
                            .password(DEV_PWD)
                            .roles("ADMIN").build()

【问题讨论】:

  • 你尝试过 Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal(); if (principal instanceof UserDetails) userName = ((UserDetails)principal).getUsername(); ?
  • 如果您需要使用自定义用户,您必须实现自己的UserDetailsService,如另一个问题中所述。如果不需要自定义用户,可以使用 Spring Security 的用户。

标签: java spring spring-mvc spring-boot spring-security


【解决方案1】:

你可以使用org.springframework.security.core.userdetails.User

String username = DEV_USER;
String encodedPassword = //encoded password
List<SimpleGrantedAuthority> authList = getAuthorities("ADMIN");

User user = new User(username, encodedPassword, authList);

拥有: 用户==>org.springframework.security.core.userdetails.User

SimpleGrantedAuthority==>org.springframework.security.core.authority.SimpleGrantedAuthority

然后您可以将用户对象转换为org.springframework.security.core.userdetails.UserDetails 对象

【讨论】:

    猜你喜欢
    • 2017-07-25
    • 1970-01-01
    • 2019-08-12
    • 1970-01-01
    • 2018-08-25
    • 2020-07-21
    • 2018-01-05
    • 2014-09-15
    • 1970-01-01
    相关资源
    最近更新 更多