Spring Security: Java Config does not work

前端 未结 1 1775
忘掉有多难
忘掉有多难 2021-02-06 04:55

I am trying to set up a java configurated spring environment including spring security. The application starts without any error, but I am not able to login succeffully.

<
1条回答
  •  南方客
    南方客 (楼主)
    2021-02-06 05:29

    Working Solution:

    Finally I found a working solution with your help. Thanks for this. Following all needed Files if someone other is interested in a java configured spring security:

    Login JSP:

    SecurityConfig.java

    @Configuration
    @EnableWebSecurity
    @EnableGlobalMethodSecurity(securedEnabled=true, prePostEnabled=true)
    public class SecurityConfig extends WebSecurityConfigurerAdapter {
    
        @Autowired private UserDetailsService userDetailService;
        @Autowired private DataSource dataSource;
    
        @Override
        public void configure(WebSecurity web) throws Exception {
            web
                .ignoring()
                    .antMatchers("/js/**","/css/**","/img/**","/webjars/**","/pages/**");
        }
    
        @Override
        public void configure(AuthenticationManagerBuilder auth) throws Exception {
            ShaPasswordEncoder shaPasswordEncoder = new ShaPasswordEncoder(256);
            auth
              .jdbcAuthentication()
                  .dataSource(dataSource)
                  .usersByUsernameQuery(getUserQuery())
                  .authoritiesByUsernameQuery(getAuthoritiesQuery())
                  .passwordEncoder(shaPasswordEncoder);
        }
    
        @Bean 
        @Override
        public AuthenticationManager authenticationManagerBean() throws Exception {
             return super.authenticationManagerBean();
        }
    
        @Override
        public void configure(HttpSecurity http) throws Exception {
            http
            .authorizeRequests()
                .anyRequest().hasAuthority("BASIC_PERMISSION")
                .and()
            .formLogin()
                .loginPage("/login/login")
                .defaultSuccessUrl("/login/success-login", true)
                .failureUrl("/login/error-login")
                .loginProcessingUrl("/login/process-login")
                .usernameParameter("security_username")
                .passwordParameter("security_password")
                .permitAll() 
                .and()
            .logout()
                .logoutSuccessUrl("/login/login")
                .logoutUrl("/login/logout")
                .permitAll()
                .and()
            .rememberMe()
                .key("your_key")
                .rememberMeServices(rememberMeServices())
                .and()
            .csrf()
                .disable();
        }
    
        @Bean
        public RememberMeServices rememberMeServices() {
            // Key must be equal to rememberMe().key() 
            TokenBasedRememberMeServices rememberMeServices = new TokenBasedRememberMeServices("your_key", userDetailService);
            rememberMeServices.setCookieName("remember_me_cookie");
            rememberMeServices.setParameter("remember_me_checkbox");
            rememberMeServices.setTokenValiditySeconds(2678400); // 1month
            return rememberMeServices;
        }
    
        @Bean
        public UserDetailsService userDetailService() {
            return new SecurityUserDetailService();
        }
    
        private String getUserQuery() {
            return "SELECT username as username, password as password, active as enabled "
                    + "FROM employee "
                    + "WHERE username = ?";
        }
    
        private String getAuthoritiesQuery() {
            return "SELECT DISTINCT employee.username as username, permission.name as authority "
                    + "FROM employee, employee_role, role, role_permission, permission "
                    + "WHERE employee.id = employee_role.employee_id "
                    + "AND role.id = employee_role.role_id "
                    + "AND role.id = role_permission.role_id "
                    + "AND permission.id = role_permission.permission_id "
                    + "AND employee.username = ? "
                    + "AND employee.active = 1";
        }
    }
    

    LoginController.java

    @Controller
    @RequestMapping("/login")
    public class LoginController {
    
        @RequestMapping(value={"/login"}, method=RequestMethod.GET)
        public ModelAndView showLoginPage() {
            return new ModelAndView("loginForm");
        }
    
        @RequestMapping(value="/success-login", method=RequestMethod.GET)  
        public String successLogin() {  
            return "forward:/dashboard/dashboard";
        } 
    
        @RequestMapping(value="/error-login", method=RequestMethod.GET)  
        public ModelAndView invalidLogin() {  
            ModelAndView modelAndView = new ModelAndView("loginForm");  
            modelAndView.addObject("error", true);  
            return modelAndView;  
        }  
    
        @RequestMapping(value="/logout", method=RequestMethod.POST)  
        public ModelAndView logout() {  
            return new ModelAndView("dashboardForm");
        }  
    }
    

    Update 1: SecurityUserDetailService

    @Service
    @Transactional
    public class SecurityUserDetailService implements UserDetailsService {
    
        @Autowired private EmployeeService employeeService;
    
        @Override
        public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
            try {
                Employee loggedInEmployee = employeeService.findEmployeeByUsername(username);
                List authorities = getAuthorities(loggedInEmployee);
                boolean enabled = true;
                boolean accountNonExpired = true;
                boolean credentialsNonExpired = true;
                boolean accountNonLocked = true;
                return new User(
                        loggedInEmployee.getUsername(),
                        loggedInEmployee.getPassword().toLowerCase(),
                        enabled,
                        accountNonExpired,
                        credentialsNonExpired,
                        accountNonLocked,
                        authorities);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }
    
        private static List getAuthorities(Employee employee) {
            List authorities = new ArrayList();
            for (Role role : employee.getRoles()) {
                for (Permission permission : role.getPermissions()) {
                    authorities.add(new SimpleGrantedAuthority(permission.getName()));
                }
            }
            return authorities;
        }
    
    }
    

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