结合使用Spring Web Security和JSON Web令牌

时间:2019-04-10 13:59:55

标签: spring-boot spring-mvc spring-security resttemplate restful-authentication

我有一个SpringBoot 2.1.4.RELEASE RESTful Web Service应用程序,该应用程序使用Spring Initializer,嵌入式Tomcat,Thymeleaf模板引擎并将其打包为可执行JAR文件,

我有这个WebSecurityConfig文件:

@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    private static final Logger LOG = LoggerFactory.getLogger(WebSecurityConfig.class);

    @Autowired
    private UserSecurityService userSecurityService;

    @Autowired
    private Environment env;

    @Value("${server.servlet.context-path}")
    private String serverContextPath;

    /** The encryption SALT. */
    private static final String SALT = "fd&dsab3";

    @Bean
    public BCryptPasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder(12, new SecureRandom(SALT.getBytes()));
    }



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

        final List<String> activeProfiles = Arrays.asList(env.getActiveProfiles());
        if (activeProfiles.contains("dev")) {
            http.csrf().disable();
            http.headers().frameOptions().disable();
        }

        http
                .authorizeRequests()
                .antMatchers(publicMatchers()).permitAll()
                .anyRequest().authenticated()
                .and()
                .formLogin().loginPage("/login").defaultSuccessUrl("/guerrilla/list")
                .failureUrl("/login?error").permitAll()
                .and()
                .logout().permitAll();
    }

    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
        auth
                .userDetailsService(userSecurityService)
                .passwordEncoder(passwordEncoder());
    }


    private String[] publicMatchers() {

         /** Public URLs. */
        final String[] PUBLIC_MATCHERS = {
                "/webjars/**",
                serverContextPath + "/css/**",
                serverContextPath + "/js/**",
                serverContextPath + "/fonts/**",
                serverContextPath + "/images/**",                
                serverContextPath ,
                "/",
                "/error/**/*",
                "/console/**",
                SignupController.SIGNUP_URL_MAPPING,
                SignupController.USER_VALIDATION_URL_MAPPING
        };

        return PUBLIC_MATCHERS;

    }

并使用此控制器:

@Controller
public class LoginController  {


    /** The login view name */
    public static final String LOGIN_VIEW_NAME = "login/login";

    @RequestMapping(value={ "/", "/login"}, method = {RequestMethod.GET})
    public String login() {     
        return serverContextPath + "/" + LOGIN_VIEW_NAME;
    }
}

我还需要凭据(用户名,密码)才能连接到API并生成de JWT令牌,但是我不知道如何获取纯文本凭据,而又会丢失Spring Security中的高级授权功能

0 个答案:

没有答案