【问题标题】:Spring boot basic authenticationSpring Boot 基本认证
【发布时间】:2018-02-14 08:17:09
【问题描述】:

我正在使用 Spring Boot Security 来帮助我进行身份验证...

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-security</artifactId>
</dependency>



@Configuration
@EnableWebSecurity
public class SpringSecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
        .cors().and().csrf().disable().authorizeRequests()
        .anyRequest().authenticated().and().httpBasic();
    }
}

我有一项用于登录(在我的控制器上)的休息服务,这是我发送电子邮件和密码的发布请求,我喜欢使用此服务进行身份验证...

但我是 spring-boot / java 的新手...有人可以帮我做正确的方法吗?

谢谢。

【问题讨论】:

    标签: spring-boot spring-security basic-authentication


    【解决方案1】:

    在 SpringSecurityConfig.java 中更改 add 方法,如下所示

        @Configuration
        @EnableWebSecurity
        public class SpringSecurityConfig extends WebSecurityConfigurerAdapter {
        @Autowired
        private UserAuthenticationService userAuthenticationService;
    
        @Autowired
        private CustomAuthenticationProvider authenticationProvider;
    
        @Autowired
        public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
            auth.authenticationProvider(this.authenticationProvider).userDetailsService(this.userAuthenticationService);
        }
    
        @Override
        protected void configure(HttpSecurity http) throws Exception {
            http
            .cors().and().csrf().disable().authorizeRequests()
            .anyRequest().authenticated().and().httpBasic();
        }}
    

    创建 CustomAuthenticationProvider。

        @Component
    public class CustomAuthenticationProvider implements AuthenticationProvider {
    
        @Autowired
        private UserAuthenticationService userAuthenticationService;
    
        @Override
        public boolean supports(Class<?> authentication) {
            return (UsernamePasswordAuthenticationToken.class.isAssignableFrom(authentication));
        }
    
        @Override
        public Authentication authenticate(Authentication authentication) throws AuthenticationException {
            String emailId = authentication.getName();
            String password = (String) authentication.getCredentials();
            UserDetails user = this.userAuthenticationService.loadUserByUsername(emailId);
            if (user == null) {
                throw new UsernameNotFoundException("Username not found.");
            }
            //Your password encoder here
            if (!password.equals(user.getPassword())) {
                throw new UsernameNotFoundException("Wrong password.");
            }
            Collection<? extends GrantedAuthority> authorities = user.getAuthorities();
            return new UsernamePasswordAuthenticationToken(user, password, authorities);
        }}
    

    创建自定义用户服务

        @Service
    public class UserAuthenticationService implements UserDetailsService {
        @Autowired
        private UserRepository userRepository;
    
        @Override
        public UserDetails loadUserByUsername(String email) throws UsernameNotFoundException {
            User user = userRepository.findByEmailAddressWithRole(email);
            if (user == null) {
                throw new UsernameNotFoundException("Username not found for " + email);
            }
            List<GrantedAuthority> grantedAuthorities = new ArrayList<GrantedAuthority>();
            for (Role roles : user.getRoles()) {
                grantedAuthorities.add(new SimpleGrantedAuthority(roles.getRoleName()));
            }
            return new UserAuthenticationWrapperDto(user.getId(), user.getEmailAddress(), user.getPassword(),
                    user.getUserType(), user.getCompany().getId(), grantedAuthorities,user.getName());
        }}   
    

    【讨论】:

      【解决方案2】:

      您需要允许访问登录端点(至少)。例如。

      @Override
      protected void configure(HttpSecurity http) throws Exception {
          http.authorizeRequests().antMatchers("/login", "/error").permitAll()
                  .antMatchers("/**").authenticated().and().exceptionHandling()
                  .authenticationEntryPoint(new LoginUrlAuthenticationEntryPoint("/login"));
      }
      

      如果我是你,我也会删除 @EnableWebSecurity(让 Spring Boot 完成它的工作)。然后在登录端点中,您需要设置安全上下文,例如

      @PostMapping
      public void authenticate(@RequestParam Map<String, String> map,
              HttpServletRequest request, HttpServletResponse response) throws Exception {
          Authentication result = authService.authenticate(map.get("username"), map.get("password"));
          SecurityContextHolder.getContext().setAuthentication(result);
          handler.onAuthenticationSuccess(request, response, result);
      }
      

      如果用户无法通过身份验证,authService 应该抛出 BadCredentialsException。这是我曾经在博客中使用的示例应用程序:https://github.com/dsyer/mustache-sample/blob/7be8459173d0b65b6d44d05f86e581d358ea9b2e/src/main/java/com/example/DemoApplication.java#L177

      【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-11-14
      • 2019-02-02
      • 2018-09-07
      • 2018-09-04
      • 1970-01-01
      • 2018-04-13
      • 2019-04-25
      相关资源
      最近更新 更多