Spring boot basic authentication

后端 未结 3 1964
一整个雨季
一整个雨季 2020-12-18 13:13

I\'m using spring boot security to help me to make authentication...


    org.springframework.boot
    

        
相关标签:
3条回答
  • 2020-12-18 13:42

    I would start by reading the spring boot security documentation. Below you will find a link.

    https://docs.spring.io/spring-security/site/docs/current/guides/html5/helloworld-boot.html

    0 讨论(0)
  • 2020-12-18 13:46

    Change add method in SpringSecurityConfig.java like Below

        @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();
        }}
    

    Create 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);
        }}
    

    Create Custom UserService

        @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());
        }}   
    
    0 讨论(0)
  • 2020-12-18 14:00

    You need to permit access to the login endpoint (at least). E.g.

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

    If I were you I would remove the @EnableWebSecurity (and let Spring Boot do it's job) as well. And then in the login endpoint you need to set the security context, e.g.

    @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);
    }
    

    The authService should throw BadCredentialsException if the user cannot be authenticated. Here's a sample app that I used in a blog once: https://github.com/dsyer/mustache-sample/blob/7be8459173d0b65b6d44d05f86e581d358ea9b2e/src/main/java/com/example/DemoApplication.java#L177

    0 讨论(0)
提交回复
热议问题