Home>

I'm studying Ionic and Spring Boot.
I am testing whether I can communicate with Java programs implemented in Spring Tool Suite using an Android application created with Ionic in my local environment at home.
Spring Security is also installed to set access authority after confirming communication.

registration.page.ts

import {HTTP} from'@ ionic-native/http/ngx';
const HEADERS = {
  "Content-Type": "application/json;"
};
@Component ({{
  selector:'app-registration',
  templateUrl:'./registration.page.html',
  styleUrls: ['./registration.page.scss'],


})
export class RegistrationPage implements OnInit {
  constructor (
    private http: HTTP,
  ) {}
  ngOnInit () {
  }
  register () {
     let name = "user1";
     let password = "password";
     let data = {
       name: name,
       password: password,
     }
     this.http.setDataSerializer ('json');
     this.http.post ('http: // (Mac IP address): 8080/register', data, HEADERS) .then ((data) =>{
       alert ("Registration successful")
     }) .catch ((error) =>{
       alert ("Registration error:" + JSON.stringify (error))
     });
  }
}

SampleController.java

 @RequestMapping (value = "/ register", method = RequestMethod.POST, produces = "application/json;charset = UTF-8")
   public ResponseEntity<String>register (@Requestbody request) {
       // First check if you can receive the request
       System.out.println ("Request received.");
      // Implement TODO membership registration process
     return new ResponseEntity<>("{}", HttpStatus.OK);
   }

AppSecurityConfig.java

@Configuration
@EnableWebSecurity
public class AppSecurityConfig extends WebSecurityConfigurerAdapter {
    @Override
    public void configure (WebSecurity web) throws Exception {
        web.ignoring (). antMatchers ("/ css/**", "/ js/**");
        web.httpFirewall (new AppHttpFirewall (sessionRegistry));
    }
    @Override
    protected void configure (HttpSecurity http) throws Exception {http.sessionManagement ()
            .maximumSessions (1)
            .maxSessionsPreventsLogin (true)
            .sessionRegistry (sessionRegistry ())
        .and ()
        .sessionFixation () .newSession ();
        http.authorizeRequests ()
            .mvcMatchers (HttpMethod.GET, "/") .permitAll ()
            .mvcMatchers (HttpMethod.POST, "/ register", "/ authenticate") .permitAll ()
            .anyRequest (). authenticated ();
        http.formLogin ()
            .loginProcessingUrl ("/ authenticate") // Login processing URL
            .failureHandler (new AppAuthenticationFailureHandler ()) // When authentication fails
            .successHandler (new AppAuthenticationSuccessHandler ())
            .usernameParameter ("name")
            .passwordParameter ("password")
            .permitAll ();
        }
}

AppHttpFirewall.java

public class AppHttpFirewall extends StrictHttpFirewall {
// private static final Logger logger = LoggerFactory.getLogger ("test_log");
    private SessionRegistry sessionRegistry;
    public AppHttpFirewall (SessionRegistry sessionRegistry) {
        super ();
        this.sessionRegistry = sessionRegistry;
        return;
    }
    @Override
    public FirewalledRequest getFirewalledRequest (HttpServletRequest request) throws RequestRejectedException {
        System.out.println ("Detected request URL:" + request.getRequestURL ());
        String userId = "";
        String cookieCerfToken = null;
        String userAgent = request.getHeader ("user-agent");
        Cookie csrfToken = WebUtils.getCookie (request, "_csrf");
        if (Objects.nonNull (csrfToken)) {
            cookieCerfToken = csrfToken.getValue ();
        }
        // Get user information from session registry and get user ID
        SessionInformation sessionInfo = sessionRegistry.getSessionInformation (request.getSession (). GetId ());
        if (Objects.nonNull (sessionInfo)) {
            Object principal = sessionInfo.getPrincipal ();
            if (principal instanceof UserDetails) {
                DMUser user = (DMUser) principal;
                userId = user.getUser (). getUserId ();
            }
        }
        try {
            return super.getFirewalledRequest (request);
        } catch (RequestRejectedException e) {
            // Clear credentials
            SecurityContextHolder.clearContext ();
            request.getSession (). Invalidate ();
            // logger.error ("Request URL invalid")
            return new FirewalledRequest (request) {@Override
                public void reset () {
                    return;
                }
            };
        }
    }
    @Override
    public HttpServletResponse getFirewalledResponse (HttpServletResponse response) {
        // TODO auto-generated method stub
        return super.getFirewalledResponse (response);
    }
}

AppAuthenticationProvider.java

public class AppAuthenticationProvider extends AbstractUserDetailsAuthenticationProvider {
    @Override
    protected UserDetails retrieveUser (String username, UsernamePasswordAuthenticationToken authentication)
            throws AuthenticationException {
        System.out.println ("username:" + username);
        System.out.println ("password:" + authentication.getCredentials (). toString ());
        // Throw an exception once to check the operation
        throw new AuthenticationException ("Login failed") {
           /**
             *
             * /
            private static final long serialVersionUID = 1L;
        };
    }
}

pom.xml

 (abridgement)<dependency><groupId>org.springframework.security</groupId>   spring-security-web</artifactId><version>5.3.4.RELEASE</version></dependency><dependency><groupId>org.springframework.security</groupId>   spring-security-config</artifactId><version>5.3.4.RELEASE</version></dependency> (abridgement)

After starting Tomcat with Spring Tool Suite so that it can accept external requests, I installed the Android application created with Ionic on the smartphone for operation check and executed the request, but the following error occurred.
Registration error:
{"status": -1, "error": "There was an error with the request: failed to connect to/[Mac IP address] (port 8080): connect failed: ECONNREFUSED (Connection refused)"}

I was able to connect by deleting the Spring Security setting from pom.xml.
After investigating, it is necessary to describe the host name.local in the host file in order to accept external connections on Mac.
I made the following settings.
127.0.0.1 localhost (hostname) .local
:: 1 localhost (hostname) .local

I made the above settings, restarted my Mac, and then tried it, but the request execution failed.
Isn't the setting when Spring Security installed insufficient?

Would you please answer if i am familiar with Spring Security settings?

  • Answer # 1

    There was an error in the implementation, so when I reviewed it, I was able to solve the problem.

  • Answer # 2

    If you just installed Spring Security and the Spring Security settings are not written, the default authentication settings will be activated for the entire application, and you will be redirected to/login to display the login page.

Related articles