Spring Security: Difference between revisions

From Chorke Wiki
Jump to navigation Jump to search
(Created page with "<source lang="properties"> ;oauth access token and refresh token oauth_refresh_token:org.springframework.security.oauth2.provider.token.store.JdbcTokenStore oauth_access_token...")
 
 
(18 intermediate revisions by the same user not shown)
Line 19: Line 19:
;
;
;persistent login/remember me
;persistent login/remember me
persistent_logins:
persistent_logins:org.springframework.security.web.authentication.rememberme.JdbcTokenRepositoryImpl
</source>
 
<source lang="java" highlight="1-7,59-64" line>
@Configuration
@EnableWebSecurity
@Import({WebDatasourceConfig.class})
@EnableConfigurationProperties(SecurityProperties.class)
@ComponentScan(basePackages = "org.chorke.academia.auth.security")
@EnableGlobalMethodSecurity(securedEnabled = true, prePostEnabled = true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
 
    @Autowired
    private DataSource dataSource;
    @Autowired
    private SecurityProperties securityProperties;
    @Autowired
    private UserDetailsService userDetailsService;
    @Autowired
    private RestAuthenticationSuccessHandler restAuthenticationSuccessHandler;
    @Autowired
    private RestAuthenticationFailureHandler restAuthenticationFailureHandler;
 
 
    @Override
    protected void configure(final HttpSecurity http) throws Exception {
        http.authorizeRequests()
                .antMatchers(securityProperties.getPattern()).permitAll()
                .and()
                    .formLogin()
                        .loginPage(securityProperties.getLoginPage())
                        .successHandler(restAuthenticationSuccessHandler)
                        .failureHandler(restAuthenticationFailureHandler)
                        .usernameParameter(securityProperties.getUsernameParameter())
                        .passwordParameter(securityProperties.getPasswordParameter())
                .and()
                    .logout()
                        .invalidateHttpSession(securityProperties.isInvalidateHttpSession())
                        .clearAuthentication(securityProperties.isClearAuthentication())
                        .logoutRequestMatcher(new AntPathRequestMatcher(securityProperties.getLogoutRequestMatcher()))
                        .logoutSuccessUrl(securityProperties.getLogoutSuccessUrl())
                .and()
                    .sessionManagement()
                        .invalidSessionUrl(securityProperties.getInvalidSessionUrl())
                        .sessionCreationPolicy(SessionCreationPolicy.IF_REQUIRED)
                        .maximumSessions(securityProperties.getMaximumSessions())
                        .expiredUrl(securityProperties.getExpiredUrl()).and()
                .and()
                    .rememberMe()
                        .rememberMeParameter(securityProperties.getRememberMeParameter())
                        .rememberMeCookieName(securityProperties.getRememberMeCookieName())
                        .tokenValiditySeconds(securityProperties.getTokenValiditySeconds())
                        .tokenRepository(persistentTokenRepository())
                .and()
                    .csrf().disable();
    }
 
    @Autowired
    public void configureGlobal(final AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder());
    }
 
    @Bean
    public PersistentTokenRepository persistentTokenRepository() {
        final JdbcTokenRepositoryImpl impl = new JdbcTokenRepositoryImpl();
        impl.setDataSource(dataSource);
        return impl;
    }
 
    @Bean
    public BCryptPasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder(securityProperties.getStrengthPasswordEncoder());
    }
 
    @Bean
    public HttpSessionEventPublisher httpSessionEventPublisher() {
        return new HttpSessionEventPublisher();
    }
}
</source>
 
==Sign In==
<source lang="bash">
curl -i --data "j_username=admin&j_password=right" https://api.chorke.org/auth/j_spring_security_check
HTTP/1.1 302
X-Content-Type-Options: nosniff
X-XSS-Protection: 1; mode=block
Cache-Control: no-cache, no-store, max-age=0, must-revalidate
Pragma: no-cache
Expires: 0
X-Frame-Options: SAMEORIGIN
Set-Cookie: JSESSIONID=84D119A4D9C890AA8A240F45A7CF4CD1; Path=/auth; HttpOnly
Location: https://api.chorke.org/auth/
Content-Length: 0
Date: Sat, 30 Nov 2019 07:54:33 GMT
</source>
<source lang="bash">
curl -i --data "j_username=admin&j_password=wrong" https://api.chorke.org/auth/j_spring_security_check
HTTP/1.1 302
X-Content-Type-Options: nosniff
X-XSS-Protection: 1; mode=block
Cache-Control: no-cache, no-store, max-age=0, must-revalidate
Pragma: no-cache
Expires: 0
X-Frame-Options: SAMEORIGIN
Set-Cookie: JSESSIONID=37D858285557F60465AE490F378FB8B3; Path=/auth; HttpOnly
Location: https://api.chorke.org/auth/account/signin?error=true
Content-Length: 0
Date: Sat, 30 Nov 2019 07:56:11 GMT
</source>
</source>


Line 25: Line 133:
{|
{|
| valign="top" |
| valign="top" |
* [https://www.baeldung.com/spring-security-create-new-custom-security-expression A Custom Security Expression with Spring Security]
* [http://code-addict.pl/permission-evaluator-boot2 Custom PermissionEvaluator in Spring Boot 2.0]
* [https://stackoverflow.com/questions/26549389 When should I implement Spring Security ACL?]
* [https://stackoverflow.com/questions/42054384 Configure oAuth2 with password flow Swagger]
* [https://stackoverflow.com/questions/42054384 Configure oAuth2 with password flow Swagger]
* [https://stackoverflow.com/questions/12537851/ Accessing spring beans in static method]
* [https://blog.marcosbarbero.com/oauth2-centralized-authorization-opaque-jdbc-spring-boot2 Centralized Authorization with OAuth2]
* [https://blog.marcosbarbero.com/oauth2-centralized-authorization-opaque-jdbc-spring-boot2 Centralized Authorization with OAuth2]
* [[Build LDAP Docker Image from Ubuntu]]
* [https://www.baeldung.com/spring-security-expressions Intro to Spring Security Expressions]
* [https://docs.spring.io/spring-security/site/docs/5.0.x/reference/html/appendix-schema.html#persistent-login-remember-me-schema Persistent Login (Remember-Me)]
* [https://docs.spring.io/spring-security/site/docs/5.0.x/reference/html/appendix-schema.html#persistent-login-remember-me-schema Persistent Login (Remember-Me)]
* [https://github.com/spring-projects/spring-android-samples Spring for Android Samples]
| valign="top" |
* [https://stackoverflow.com/questions/22767205/ Spring Security » Exclude URL Patterns From Config]
* [https://stackoverflow.com/questions/10822951/ Get a property value from an ApplicationContext]
* [https://keepgrowing.in/tools/how-to-add-x-xsrf-token-header-to-postman-requests/ Add X-XSRF-TOKEN header to Postman requests]
| valign="top" |
|-
| colspan="3" |
----
|-
| valign="top" |
* [[Spring Cloud OpenFeign]]
* [[Postman Script]]
* [[HTTP Security]]
* [[Keycloak]]
* [[LDAP]]
| valign="top" |
| valign="top" |
|}
|}

Latest revision as of 19:40, 7 February 2024

;oauth access token and refresh token
oauth_refresh_token:org.springframework.security.oauth2.provider.token.store.JdbcTokenStore
oauth_access_token:org.springframework.security.oauth2.provider.token.store.JdbcTokenStore
oauth_approvals:org.springframework.security.oauth2.provider.approval.JdbcApprovalStore
;
;oauth client authentication and authorization
oauth_client_details:org.springframework.security.oauth2.provider.client.JdbcClientDetailsService
oauth_client_token:org.springframework.security.oauth2.client.token.JdbcClientTokenServices
oauth_code:org.springframework.security.oauth2.provider.code.JdbcAuthorizationCodeServices
;domain object security
acl_object_identity:org.springframework.security.acls.jdbc.JdbcMutableAclService
acl_entry:org.springframework.security.acls.jdbc.JdbcMutableAclService
acl_class:org.springframework.security.acls.jdbc.JdbcMutableAclService
acl_sid:org.springframework.security.acls.jdbc.JdbcMutableAclService
;
;persistent login/remember me
persistent_logins:org.springframework.security.web.authentication.rememberme.JdbcTokenRepositoryImpl
@Configuration
@EnableWebSecurity
@Import({WebDatasourceConfig.class})
@EnableConfigurationProperties(SecurityProperties.class)
@ComponentScan(basePackages = "org.chorke.academia.auth.security")
@EnableGlobalMethodSecurity(securedEnabled = true, prePostEnabled = true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private DataSource dataSource;
    @Autowired
    private SecurityProperties securityProperties;
    @Autowired
    private UserDetailsService userDetailsService;
    @Autowired
    private RestAuthenticationSuccessHandler restAuthenticationSuccessHandler;
    @Autowired
    private RestAuthenticationFailureHandler restAuthenticationFailureHandler;


    @Override
    protected void configure(final HttpSecurity http) throws Exception {
        http.authorizeRequests()
                .antMatchers(securityProperties.getPattern()).permitAll()
                .and()
                    .formLogin()
                        .loginPage(securityProperties.getLoginPage())
                        .successHandler(restAuthenticationSuccessHandler)
                        .failureHandler(restAuthenticationFailureHandler)
                        .usernameParameter(securityProperties.getUsernameParameter())
                        .passwordParameter(securityProperties.getPasswordParameter())
                .and()
                    .logout()
                        .invalidateHttpSession(securityProperties.isInvalidateHttpSession())
                        .clearAuthentication(securityProperties.isClearAuthentication())
                        .logoutRequestMatcher(new AntPathRequestMatcher(securityProperties.getLogoutRequestMatcher()))
                        .logoutSuccessUrl(securityProperties.getLogoutSuccessUrl())
                .and()
                    .sessionManagement()
                        .invalidSessionUrl(securityProperties.getInvalidSessionUrl())
                        .sessionCreationPolicy(SessionCreationPolicy.IF_REQUIRED)
                        .maximumSessions(securityProperties.getMaximumSessions())
                        .expiredUrl(securityProperties.getExpiredUrl()).and()
                .and()
                    .rememberMe()
                        .rememberMeParameter(securityProperties.getRememberMeParameter())
                        .rememberMeCookieName(securityProperties.getRememberMeCookieName())
                        .tokenValiditySeconds(securityProperties.getTokenValiditySeconds())
                        .tokenRepository(persistentTokenRepository())
                .and()
                    .csrf().disable();
    }

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

    @Bean
    public PersistentTokenRepository persistentTokenRepository() {
        final JdbcTokenRepositoryImpl impl = new JdbcTokenRepositoryImpl();
        impl.setDataSource(dataSource);
        return impl;
    }

    @Bean
    public BCryptPasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder(securityProperties.getStrengthPasswordEncoder());
    }

    @Bean
    public HttpSessionEventPublisher httpSessionEventPublisher() {
        return new HttpSessionEventPublisher();
    }
}

Sign In

curl -i --data "j_username=admin&j_password=right" https://api.chorke.org/auth/j_spring_security_check
HTTP/1.1 302
X-Content-Type-Options: nosniff
X-XSS-Protection: 1; mode=block
Cache-Control: no-cache, no-store, max-age=0, must-revalidate
Pragma: no-cache
Expires: 0
X-Frame-Options: SAMEORIGIN
Set-Cookie: JSESSIONID=84D119A4D9C890AA8A240F45A7CF4CD1; Path=/auth; HttpOnly
Location: https://api.chorke.org/auth/
Content-Length: 0
Date: Sat, 30 Nov 2019 07:54:33 GMT
curl -i --data "j_username=admin&j_password=wrong" https://api.chorke.org/auth/j_spring_security_check
HTTP/1.1 302
X-Content-Type-Options: nosniff
X-XSS-Protection: 1; mode=block
Cache-Control: no-cache, no-store, max-age=0, must-revalidate
Pragma: no-cache
Expires: 0
X-Frame-Options: SAMEORIGIN
Set-Cookie: JSESSIONID=37D858285557F60465AE490F378FB8B3; Path=/auth; HttpOnly
Location: https://api.chorke.org/auth/account/signin?error=true
Content-Length: 0
Date: Sat, 30 Nov 2019 07:56:11 GMT

References