Spring Security 如何获取用户电子邮件地址?

olqngx59  于 2021-07-23  发布在  Java
关注(0)|答案(3)|浏览(373)

如何在控制器中获取用户电子邮件地址?
我正在尝试获取控制器中试图登录的用户的电子邮件地址,但由于某些原因被阻止。我想通知用户,此电子邮件地址的用户已被阻止。但是为了这个,我需要得到他的电子邮件地址。
问题!如何在控制器中获取用户电子邮件地址?
我有securityconfig,userdetail,logincontroller。
在这里我添加了整个项目-https://github.com/romanych2021/mytest 专门为这个问题做的
证券配置

package com.mytest.security;

    import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
    import org.springframework.security.config.annotation.web.builders.HttpSecurity;
    import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
    import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
    import org.springframework.security.core.userdetails.UserDetailsService;

    @EnableWebSecurity
    public class SecurityConfig extends WebSecurityConfigurerAdapter {

        private final
        UserDetailsService userDetailsService;

        public SecurityConfig(UserDetailsService userDetailsService) {
            this.userDetailsService = userDetailsService;
        }

        @Override
        protected void configure(AuthenticationManagerBuilder auth) throws Exception {
            auth.userDetailsService(userDetailsService);
        }

        @Override
        protected void configure(HttpSecurity http) throws Exception {
            http
                    .authorizeRequests()

                    .mvcMatchers("/login").anonymous()
                    .mvcMatchers("/user/**").hasRole("USER")

                    .and()
                    .csrf().disable()
                    .formLogin()
                    .loginPage("/login")
                    .loginProcessingUrl("/login")
                    .defaultSuccessUrl("/")
                    .failureUrl("/login?error=true")
                    .usernameParameter("email")
                    .passwordParameter("password")

                    .and()
                    .exceptionHandling()
                    .accessDeniedPage("/403")

                    .and()
                    .logout()
                    .permitAll()
                    .logoutUrl("/logout")
                    .logoutSuccessUrl("/")

                    .invalidateHttpSession(true)
                    .deleteCookies("JSESSIONID");
        }

    }

用户详细信息

package com.mytest.security;

    import com.mytest.model.User;
    import com.mytest.service.UserRepository;

    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.security.core.GrantedAuthority;
    import org.springframework.security.core.authority.SimpleGrantedAuthority;
    import org.springframework.security.core.userdetails.UserDetails;
    import org.springframework.security.core.userdetails.UserDetailsService;
    import org.springframework.security.core.userdetails.UsernameNotFoundException;
    import org.springframework.stereotype.Service;

    import java.util.ArrayList;
    import java.util.Collection;
    import java.util.List;

    @Service
    public class UserDetail implements UserDetailsService {

        @Autowired
        UserRepository userRepository;

        @Override
        public UserDetails loadUserByUsername(String email) throws UsernameNotFoundException {

            User user = userRepository.findUserByEmail(email);

            if (user == null){
                throw new UsernameNotFoundException("There is no such user " + email);
            }

            return new org.springframework.security.core.userdetails.User(
                    user.getEmail(),
                    user.getPassword(),
                    user.getEnabled(),
                    user.getAccount_non_expired(),
                    user.getCredentials_non_expired(),
                    user.getAccount_non_locked(),
                    getAuthorities());

        }

        private Collection<? extends GrantedAuthority> getAuthorities(){

            List<SimpleGrantedAuthority> authList = new ArrayList<>();
            authList.add(new SimpleGrantedAuthority("ROLE_USER"));

            return authList;

        }

    }

登录控制器

package com.mytest.controller;

    import org.springframework.stereotype.Controller;
    import org.springframework.web.bind.annotation.GetMapping;

    @Controller
    public class LoginController {

        @GetMapping(value = "/login")
        public String loginGet () {

            // How do I get the user's email address here?

            return "login";
        }

    }
83qze16e

83qze16e1#

假设您使用提供的usernamepasswordauthenticationfilter并且没有对此进行任何重写,并且用户已经登录到您的系统;您可以按以下方式访问用户名:

@GetMapping(value = "/login")
public String loginGet (Authentication auth) {
    String username = auth.getName();
    return "login";
}

spring将自动注入默认的身份验证令牌 UsernamePasswordAuthenticationToken 在这里。
编辑:似乎我错把这个问题当成已经登录了。如果这是登录失败问题,您可以执行以下操作:
步骤1:创建新的authenticationexception,如下所示:

public class UserBlockedException extends UsernameNotFoundException {
    public UserBlockedException(String msg) {
        super(msg);
    }
}

步骤2:在userdetail@service类中抛出上面的异常,并在用户被阻止时向用户显示消息。
步骤3:在login?error=true表单中显示错误消息:

<div th:if="${param.error}">
  Login Failed. Reason: <span th:text="${session["SPRING_SECURITY_LAST_EXCEPTION"].message"></span> 
</div>

spring security将使用默认值 SimpleUrlAuthenticationFailureHandler 来处理你的错误。它将异常保存为会话属性,您可以在thymeleaf中访问该属性,如步骤3所示。

c9qzyr3d

c9qzyr3d2#

public static User getCurrentUser() {
    return (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
}

您需要配置一个实现userdetails的新用户类,并让userdetailservice的loaduserbyusername方法返回此用户的示例。请参阅本文。
编辑:我误读了原文。jms修改后的答案应该可以解决您的问题。

46scxncf

46scxncf3#

据我所知,当您使用SpringSecurity时,您不需要控制器—usernamepasswordauthenticationfilter在安全筛选器链中注册并执行身份验证工作。所以我想你可以检查它,并相应地调整你的逻辑。链接

相关问题