logo
down
shadow

Spring security Oauth 2 with ajax login and form login


Spring security Oauth 2 with ajax login and form login

By : Scott Yarbrough
Date : December 01 2020, 05:00 PM
it should still fix some issue The way spring security manages form based authentication is totaly different what you are trying to achive through oauth2.0. When you are using ajax (oauth2.0) way of authenticating (which is actualy authorization process of client application by user with username and password) user, only your client application (application through which you are firing ajax request) will get authenticated through spring security filter and SecurityContextHolder will have authentication object of authenticated client application not the user. If you will see your security configuration you are allowing all the request to pass without authentication in case of non ajax login. To enable form based login you need to configure your security to protect all other url except login url... something as given below
code :
@Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf().disable().authorizeRequests()
                .antMatchers("/**")
                .authenticated().and().formLogin();
    }


Share : facebook icon twitter icon
Spring Security OAuth2 - Is it possible to using client form login instead of the authorization server's form login?

Spring Security OAuth2 - Is it possible to using client form login instead of the authorization server's form login?


By : user3348529
Date : March 29 2020, 07:55 AM
Hope that helps Anything is possible, but since the main reason for OAuth2 to have the auth code flow is to avoid that scenario, it defeats the object somewhat. What do you need OAuth2 for (maybe you should just authenticate everything locally in your app)?
Spring Security OAuth 2 with form login

Spring Security OAuth 2 with form login


By : Dylan R
Date : March 29 2020, 07:55 AM
I think the issue was by ths following , With SSO the whole point is that the user authenticates with the auth server (localhost:8081 in your case). If you want a form login, that's where you need to implement it, not in the client app.
How to configure Spring Boot and Spring Security to support both form login and Google OAuth2 login

How to configure Spring Boot and Spring Security to support both form login and Google OAuth2 login


By : laxpro2001
Date : March 29 2020, 07:55 AM
seems to work fine I am strugging to configure a Spring Boot application with Spring Security to support two login mechanisms: form login and Google OAuth2 login. , This is how I solved it using two WebSecurityConfigurerAdapters:
code :
@EnableWebSecurity
class SecurityConfig extends WebSecurityConfigurerAdapter{

    @Configuration
    @Order(1)
    static class FormLoginWebSecurityConfigurerAdapter extends WebSecurityConfigurerAdapter {

        @Override
        protected void configure(HttpSecurity http) throws Exception {
            http
                .antMatcher("/secure-home")
                .authorizeRequests()
                    .anyRequest().authenticated()
                    .and()
                .formLogin()
                    .loginPage("/login")
                    .permitAll()
        }
    }

    @Configuration
    @Order(2)
    static class OAuth2SecurityConfigurerAdapter extends WebSecurityConfigurerAdapter {

        private final String LOGIN_URL = "/googleLogin";

        @Autowired
        OAuth2ClientContextFilter oAuth2ClientContextFilter

        @Bean
        AuthenticationEntryPoint authenticationEntryPoint() {
            new LoginUrlAuthenticationEntryPoint(LOGIN_URL)
        }

        @Bean
        OpenIDConnectAuthenticationFilter openIdConnectAuthenticationFilter() {
            new OpenIDConnectAuthenticationFilter(LOGIN_URL)
        }

        @Override
        protected void configure(HttpSecurity http) throws Exception {
            http
                .addFilterAfter(oAuth2ClientContextFilter, AbstractPreAuthenticatedProcessingFilter.class)
                .addFilterAfter(openIdConnectAuthenticationFilter(), OAuth2ClientContextFilter.class)
            .exceptionHandling().authenticationEntryPoint(authenticationEntryPoint())
            .and()
                .authorizeRequests()
                    .antMatchers(GET, "/googleOAuth2").authenticated()
        }
    }
}
Spring security configure 2 kind of login behaviors - ajax response JSON & form login redirect new page

Spring security configure 2 kind of login behaviors - ajax response JSON & form login redirect new page


By : Kareem Yousry
Date : March 29 2020, 07:55 AM
around this issue Just think of simply hack by submitting additional parameter in the login form or Ajax
code :
<input type="hidden" name="responseJson" value="true"/>
String responseJson = request.getParameter("responseJson"); 
if (responseJson != null && responseJson.equals("true")){
    response.setContentType("text/json");
    PrintWriter out = response.getWriter();
    out.print(jsonObjectAboutFailLogin.toString());
    out.flush();
}
Spring with two security configurations - failed API login redirects to form login page. How to change?

Spring with two security configurations - failed API login redirects to form login page. How to change?


By : user3427607
Date : March 29 2020, 07:55 AM
should help you out I added an @Override of unsuccessfulAuthentication() to my Authentication filter
The grandparent class (AbstractAuthenticationProcessingFilter) has a method for unsuccessful authentications (i.e. AuthenticationException) which delegates to an authentication failure handler class. I could have created my own custom authentication failure handler, but instead decided to simply override the unsuccessfulAuthentication method with some code that sends back a response with a 401 status and a JSON error message:
code :
@Override
protected void unsuccessfulAuthentication(HttpServletRequest request, HttpServletResponse response, AuthenticationException e) throws IOException, ServletException {
    // TODO: enrich/improve error messages
    response.setStatus(response.SC_UNAUTHORIZED);
    response.setContentType(MediaType.APPLICATION_JSON_VALUE);
    response.setCharacterEncoding(StandardCharsets.UTF_8.toString());
    response.getWriter().write("{\"error\": \"authentication error?\"}");
}
public class RESTAuthenticationEntryPoint implements AuthenticationEntryPoint {
    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException e) throws IOException, ServletException {
        // TODO: enrich/improve error messages
        response.setStatus(response.SC_UNAUTHORIZED);
        response.setContentType(MediaType.APPLICATION_JSON_VALUE);
        response.setCharacterEncoding(StandardCharsets.UTF_8.toString());
        response.getWriter().write("{\"error\": \"unauthorized?\"}");
    }
}
@Configuration
@Order(1)
public static class APISecurityConfiguration extends WebSecurityConfigurerAdapter {

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

        JWTAuthenticationFilter jwtAuthenticationFilter = new JWTAuthenticationFilter(authenticationManager());
        jwtAuthenticationFilter.setFilterProcessesUrl("/api/login");

        http.antMatcher("/api/**")
                .sessionManagement()
                    .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                    .and()
                .csrf().disable()
                .authorizeRequests()
                    .anyRequest().authenticated()
                    .and()
                .exceptionHandling()
                    .authenticationEntryPoint(new RESTAuthenticationEntryPoint())
                    .and()
                .addFilter(jwtAuthenticationFilter)
                .addFilter(new JWTAuthorizationFilter(authenticationManager()));
    }
}
Related Posts Related Posts :
  • My shape moved but will pause for a while
  • How to solve syntax error in eclipse Mars.1
  • Shibboleth idp configuration for ldap authentication
  • Do something when app starts?
  • Android Runtime Exception font asset not found
  • How to query using objectify in Google App Engine app
  • List value is printing address instead of value
  • StringUtils.isBlank return false for null Strings
  • Sent parameter through PATCH android
  • i am not able to clear the code below given using throwable concept in java
  • How to get System time instead of Server time in java?
  • How to push json data into an arrya object in MONGO DB by java
  • Saving RelationshipEntity not working
  • Error on "instanceOf" when checking a subClass
  • Java - Splitting a image into 4 images
  • "Pinging" a server in Java
  • RoboGuice Proguard CreationException
  • Android Array list returns Null after adding values
  • Jar Executable what am I doing wrong?
  • How do I mitigate Connection leak triggered for connection com.mysql.jdbc.JDBC4Connection@11d08960,
  • How do i iterate values from a 2d array using conditions
  • Hide Button in CustomPagerAdapter
  • Java GC: does it ever make sense to call super.finalize() in a class that only extends Object?
  • 64bit HashMap in Java
  • Hibernate wildcard query on two columns
  • Want to Generate Auto Login Program Using Java
  • Parse findInBackground doesn't add to global arraylist?
  • Remove random item from ArrayList
  • in SpringMVC getMessage from i18n properties in a function outside the controller
  • How do I add JCheckBox next to each name that has been entered into an arraylist from a JTextField?
  • Return node ID along with complete node
  • InvocationTargetException. Cannot cast class X to class X. When invoked in Scala Imain through spark-submit
  • how to print elements of a 1D array into a N x N box
  • How to map csv file to pojo class in java
  • How, in Java, to encode default vhost %2F in URL/URI so it doesn't get changed to slash and fail to work
  • Tomcat 5.5 https configuration in Windows Server 2008 64bit
  • Enabling FIPS 140-2 compliance mode in MULE ESB
  • How to pass String PackageName to PkgName under parseXML() and run XMLParser class as a new activity when click on list
  • Error while creating spring -hibernate configuration file
  • Hand off control between java threads
  • NoClassDefFoundError: scala/collection/Seq
  • Getting stack overflow error on one machine but not the other on the same code
  • How can I loop AsyncAjaxRequest in GWT?
  • Failed to find provider info for urbanairship.provider
  • Android ListView Adapter Crash issue/Duplicates
  • Displaying Splash screen only once on user preference
  • Loop List<WebElement> doesn't stop despite no more WebElements
  • Check if pattern exists in a String
  • Swing - Key Problems (Arrow Keys, Tab, etc.) in GUIs with TextComponents
  • Why the solution for binary search tree validity is not working?
  • Double encrypting 2048 RSA?
  • create junit test for runnable class
  • Unable to read and sort information from a text file in Java
  • My device isn't getting detected in android studio (driver issue)
  • Representing a Graph in Java
  • How to XML mapping using jxls
  • Quick Sort stackoverflow error for large arrays
  • Parsing Apache Tika XML Output returns Unknown Tag
  • java simple UI loop, can't find bug
  • how to use greater than and less than in a single if statement in java
  • shadow
    Privacy Policy - Terms - Contact Us © animezone.co