3

目前我正在使用以下内容将用户登录到我的应用程序中。但是我想使用角度函数来实际执行登录。为此,我想创建一个休息 Web 服务来进行身份验证,但是我在 SO 上看到的所有示例都使用了我认为已弃用的用户。我还希望该服务返回有关用户的信息。

我要问的是如何将 MyUserDetailsS​​ervice 更改为用作登录的宁静服务,或者如何创建可用于登录的服务,该服务将在登录后返回用户对象。

<form class="navbar-form" action="/j_spring_security_check" method="post">
   <input class="span2" name="j_username"  type="text" placeholder="Email">
   <input class="span2" name="j_password" type="password" placeholder="Password">
   <input type="submit" class="btn btn-primary" value="Log in"/>
</form>

这是我的身份验证管理器

<authentication-manager>
    <authentication-provider user-service-ref="MyUserDetailsService">
        <password-encoder ref="passwordEncoder"/>
    </authentication-provider>
</authentication-manager>

这是我目前用于登录的用户详细信息服务。

@Service("MyUserDetailsService")
public class MyUserDetailsService implements UserDetailsService {
    private static final Logger logger = LoggerFactory.getLogger(MyUserDetailsService.class);

    private UserManager userManager;

    @Autowired
    public MyUserDetailsService(UserManager userManager) {
        this.userManager = userManager;
    }
    @Override
    @Transactional
    public UserDetails loadUserByUsername(String email) throws UsernameNotFoundException, DataAccessException {
        if ((email == null) || email.trim().isEmpty()) {
            throw new UsernameNotFoundException("Email is null or empty");
        }
        logger.debug("Checking users with email: " + email);

        Users users = userManager.findByEmail(email);

        if (users == null) {
            String errorMsg = "User with email: " + email + " could not be found";
            logger.debug(errorMsg);
            throw new UsernameNotFoundException(errorMsg);
        }

        Collection<GrantedAuthority> grantedAuthorities = toGrantedAuthorities(users.getRoleNames());
        String password = users.getPassword();
        boolean enabled = users.isEnabled();
        boolean userNonExpired = true;
        boolean credentialsNonExpired = true;
        boolean userNonLocked = true;

        return new User(email, password, enabled, userNonExpired, userNonLocked, credentialsNonExpired, grantedAuthorities);
    }

    public static Collection<GrantedAuthority> toGrantedAuthorities(List<String> roles) {
        List<GrantedAuthority> result = newArrayList();

        for (String role : roles) {
            result.add(new SimpleGrantedAuthority(role));
        }

        return result;
    }
}
4

1 回答 1

3

Spring Security有一些JSTL 标签,您可以在视图上使用这些标签来做一些事情。如果 JSTL 不是一个选项,无论出于何种原因,您都可以执行以下操作:

${pageContext.request.userPrincipal.principal.yourCustomProperty}

此外,您可以在 Controller 中获取 Principal 并将其设置在 Model 上。

于 2013-03-08T20:51:28.330 回答