springboot应用程序中可以有两个访问令牌吗?

时间:2019-08-08 14:03:37

标签: spring-boot primavera

我评论了我的应用程序的组成方式: SpringBoot + Hibernate + Multitenant(数据库主+租户的数据库)+ Postgressql。 该应用程序是公司的设备管理员,客户可以在其中向您发送信息。也就是说,设备连接到服务器并“登录”,但用户也执行“登录”。在用户端,我通过JWT解决它,生成访问令牌,然后授权它。
您可以对团队也这样做吗?让他们登录以生成其他不同的访问令牌?
如果不理解某些内容,我会再次解释,我的书面英语不是很好。抱歉。

执行 值得说明的是,登录的设备不会具有不同的“ ROLES”

这是我的类WebSecurityConfigurerAdapter

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class CustomSecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private CustomUserDetailsService userDetailsService;
    @Autowired
    private IUsuario userService;
    @Autowired
    private IUsuarioSucursalRol usrService;

    private static final String[] AUTH_LIST = {
            // -- swagger ui
            "**/swagger-resources/**", "/swagger-ui.html", "/v2/api-docs", "/webjars/**" };

    /**
     * This is where access to various resources (urls) in the application is
     * defined
     * 
     * 
     * 
     */
    @Override
    protected void configure(HttpSecurity httpSecurity) throws Exception {

        httpSecurity.authorizeRequests().antMatchers(HttpMethod.POST, "/login").permitAll().anyRequest().authenticated()
                .and().addFilter(new JWTAuthenticationFilter(authenticationManager()))
                .addFilter(new JWTAuthorizationFilter(authenticationManager(), userService, usrService));

        httpSecurity.authorizeRequests().antMatchers(AUTH_LIST).authenticated().and().httpBasic()
                .authenticationEntryPoint(swaggerAuthenticationEntryPoint()).and().csrf().disable();

    }

    /**
     * Create an instance of the custom authentication filter which intercepts and
     * processes the end user's login form submission for further authentication
     * processing. This filter is added before other filters so that it can
     * intercept the user login form submission and extract the the additional
     * 'tenant' field
     * 
     * @return
     * @throws Exception
     */
    /*
     * public CustomAuthenticationFilter authenticationFilter() throws Exception {
     * CustomAuthenticationFilter filter = new CustomAuthenticationFilter();
     * filter.setAuthenticationManager(authenticationManagerBean());
     * filter.setAuthenticationFailureHandler(failureHandler());
     * filter.setAuthenticationSuccessHandler(successHandler()); return filter; }
     */

    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
        auth.authenticationProvider(authProvider());
    }

    /**
     * Authentication provider which provides the logged in user's credentials for
     * verification and authentication if they are coeect
     * 
     * @return
     */
    public AuthenticationProvider authProvider() {
        // The custom authentication provider defined for this app
        CustomUserDetailsAuthenticationProvider provider = new CustomUserDetailsAuthenticationProvider(
                passwordEncoder(), userDetailsService);
        return provider;
    }

    /**
     * The page to show if authentication fails
     * 
     * @return
     */
    public SimpleUrlAuthenticationFailureHandler failureHandler() {
        return new SimpleUrlAuthenticationFailureHandler("/login?error=true");
    }

    public SimpleUrlAuthenticationSuccessHandler successHandler() {
        return new SimpleUrlAuthenticationSuccessHandler("/user/index");
    }

    @Bean(name = "passwordEncoder")
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    @Bean
    public BasicAuthenticationEntryPoint swaggerAuthenticationEntryPoint() {
        BasicAuthenticationEntryPoint entryPoint = new BasicAuthenticationEntryPoint();
        entryPoint.setRealmName("Swagger Realm");
        return entryPoint;
    }

}

我的JWTAuthenticationFilter是

public class JWTAuthenticationFilter extends UsernamePasswordAuthenticationFilter {

    private AuthenticationManager authenticationManager;
    @Autowired
    private BCryptPasswordEncoder bCryptPasswordEncoder;
    @Autowired
    private IUsuario iusuario;

    public JWTAuthenticationFilter(AuthenticationManager authenticationManager) {
        this.authenticationManager = authenticationManager;
    }

    @Override
    public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response)
            throws AuthenticationException {
        try {
            Usuario credenciales = new ObjectMapper().readValue(request.getInputStream(), Usuario.class);

            return authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(credenciales.getUsuario(),
                    credenciales.getPassword(), new ArrayList<>()));
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    protected void successfulAuthentication(HttpServletRequest request, HttpServletResponse response, FilterChain chain,
            Authentication auth) throws IOException, ServletException {

        String token = Jwts.builder().setIssuedAt(new Date()).setIssuer(ISSUER_INFO)
                .claim("User", ((CustomUserDetails) auth.getPrincipal()).getUsername())
                .claim("Tenant", ((CustomUserDetails) auth.getPrincipal()).getTenant().getIdTenant())
                .setExpiration(new Date(System.currentTimeMillis() + TOKEN_EXPIRATION_TIME))
                .signWith(SignatureAlgorithm.HS512, SUPER_SECRET_KEY).compact();

        response.addHeader(HEADER_AUTHORIZACION_KEY, TOKEN_BEARER_PREFIX + " " + token);
    }
}

0 个答案:

没有答案