title: Access the spring security in different ports getting principle data as a String 'anonymousUser'
body: <p>I have an application running in my local 8100 and my server side code is executed in 8065 it has implemented <code>Spring Security</code> as Java config. When I hit the login server code from 8100 ionic browser window . I got the principle object data only have string as <code>anonymousUser</code>.
    I printed in my server side code for <code>Authentication</code>  and <code>Principle</code> data. Below pasted the code .</p>
  
  <p>For <code>Authentication</code></p>
  
  <p><code>Authentication auth = SecurityContextHolder.getContext().getAuthentication()</code></p>
  
  <p><code>auth</code> data is ,</p>
  
  <p><code>org.springframework.security.authentication.AnonymousAuthenticationToken@9055c2bc: Principal: anonymousUser; Credentials: [PROTECTED]; Authenticated: true; Details: org.springframework.security.web.authentication.WebAuthenticationDetails@b364: RemoteIpAddress: 0:0:0:0:0:0:0:1; SessionId: null; Granted Authorities: ROLE_ANONYMOUS</code></p>
  
  <p>For <code>getPrincipal</code></p>
  
  <p><code>Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();</code></p>
  
  <p><code>principal</code> data</p>
  
  <p><code>anonymousUser</code> this string only it has. Below i pasted my Security config java class code .</p>
  
  <p><strong>Security Config</strong> Java Class</p>
  
  <pre><code>public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
  
      @Autowired
      DataSource dataSource;
  
      @Autowired
      private SecurityUserService userDetailsService;
  
      @Override
      public void configure(WebSecurity web) throws Exception {
          web.ignoring().antMatchers("/user/createsocialuser");
      }
  
      @Override
      public void configure(AuthenticationManagerBuilder auth) throws Exception {
          auth.userDetailsService(userDetailsService);
      }
  
  
      @Override
      protected void configure(HttpSecurity http) throws Exception {
          ExceptionMappingAuthenticationFailureHandler loginFailureHandler = new ExceptionMappingAuthenticationFailureHandler();
  
          loginFailureHandler.setDefaultFailureUrl("/login/loginFailure");
  
          http
          .authorizeRequests()
          .regexMatchers("/login.*").permitAll()
          .regexMatchers("/admin.*").hasRole("ADMIN")
          .regexMatchers("/user.*").hasRole("USER")
              .and()
              .formLogin()
              .usernameParameter("j_username") 
              .passwordParameter("j_password")
              .loginProcessingUrl("/j_spring_security_check")
              .defaultSuccessUrl("/login/loginSuccess")
              .permitAll()
              .failureHandler(loginFailureHandler)
              .permitAll().and().logout().permitAll()
              .and().exceptionHandling()
              .accessDeniedPage("/accessDenied/403").and().csrf().disable();
      }
  
  
  }
  </code></pre>
  
  <p><strong>Login Html</strong> </p>
  
  <pre><code>&lt;form class="form-horizontal" name="loginform" data-ng-submit="doLogin(loginform,userDetails)"&gt;
            &lt;label for="username"&gt;Username:&lt;/label&gt;
            &lt;input type="text" class="form-control" ng-model="$parent.login.email" id="j_username" placeholder="Enter username" name="j_username" &gt;
            &lt;label for="password"&gt;Password:&lt;/label&gt;
            &lt;input type="password" class="form-control" ng-model="$parent.login.password" id="j_password" placeholder="Enter password" type="password" name="j_password"&gt;
            &lt;div class="alert alert-danger" id="loginerror" role="alert"&gt;
              invalid usermame or password
            &lt;/div&gt;&lt;br/&gt;
  
            &lt;button type="submit" class="btn btn-default submit"&gt;Si in&lt;/button&gt;
        &lt;/form&gt;
  </code></pre>
  
  <p><strong>Login Js</strong> </p>
  
  <pre><code>$scope.doLogin = function(loginform,userDetails) {
              if (loginform.$valid) {
               console.log('$parent.login.email',angular.toJson(self.login.email));
               console.log('$parent.login.password',angular.toJson(self.login.password));
               var loc = 'http://localhost:8080/Test_10030';
                $http.post(loc+'/j_spring_security_check?j_username='+self.login.email+'&amp;j_password='+self.login.password)
               .success(function(data){ 
                     console.log('Server data =&gt;',angular.toJson(data));
                   if(data.responseError == "loginFailed"){
                       alert("user name pasword incorrect")
                         console.error('Server data =&gt;');
                       $log.log("Error login Credentials: ",JSON.stringify(data));
                       $location.url('login');
                   }
  
  
             if(data.responseSuccess == "success"){
                if(data.result != null){
                    var serverData = data.result;
                    console.warn('Server data =&gt;',angular.toJson(serverData));
                    $rootScope.userData= serverData;
                    $location.url('/home');
                }
             }
             }).error(function(data){          
              //callback 
              console.log('Error Some Internal server Error',data);
             });
               } else {
                $log.log("form is invalid!");
                if (self.isNewUser) {
                 loginform["username"].$dirty = true;
                 loginform["usrtel"].$dirty = true;
                } 
                loginform["email"].$dirty = true;
                loginform["password"].$dirty = true;
               }
              };
  </code></pre>
  
  <p><strong>Login COntroller</strong> Java</p>
  
  <pre><code> @RestController
      @RequestMapping("/login")
      public class LoginController {
          @RequestMapping(value="/loginSuccess",method = RequestMethod.GET)
          public  ResponseWrapper  create(Principal principle) {  
              System.out.println("-------***************----------------"); 
              try {
                  System.out.println("principle data=&gt;"+principle)// NULL POINTER EXCEPTION
                  System.out.println("-------sucess********----------------");
                  ResponseWrapper wrap = new ResponseWrapper();
  
                  Object principal = SecurityContextHolder.getContext().getAuthentication().getAuthorities();
                  System.err.println("Principal dara=&gt;"+principal);
                  wrap.setResult(principle);
                  wrap.setResponseSuccess("success");
                  return wrap;
              } catch (Exception e) {
                  e.printStackTrace();
              }
              return null;
          }
      }
  </code></pre>
  
  <p><strong>UserDetail Class</strong></p>
  
  <pre><code>@Service
  @Transactional
  public class SecurityUserService implements IUserService {
  
      @Autowired
      private SecurityUserDao gpuser_Dao;
  
      @Override
      public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
          System.out.println("............" + username);
          GpUser user = gpuser_Dao.findUser(username);
          UserDetails userDetails = null;
          String rol = null;
          if (user == null) {
              throw new UsernameNotFoundException("No User found");
          } else {
              List&lt;GrantedAuthority&gt; grantedAuthorities = new ArrayList&lt;GrantedAuthority&gt;();
              // Access DB and get the roles and assign
              Object obj = user.getAuthorities();
              System.out.println("obje data=&gt;" + obj.toString());
              grantedAuthorities.add(new SimpleGrantedAuthority("ROLE_ADMIN")); 
              userDetails = new User(user.getUsername(), user.getPassword(), true, true, true, true, grantedAuthorities);
              /** ADDING ROLES-Creating authentication object with roles **/
              Authentication authentication = new UserAuthenticationToken(user, userDetails,
                      userDetails.getAuthorities());
              // Set the authentication
              SecurityContextHolder.getContext().setAuthentication(authentication);
          }
          Object principal = SecurityContextHolder.getContext().getAuthentication().getAuthorities();
          return userDetails;
      }
  }
  </code></pre>
  
  <p><strong>BootSecurityUserDao .java</strong></p>
  
  <pre><code>@Repository
  @Transactional
  public class BootSecurityUserDao implements IUserDao {
  
      @PersistenceContext
      private EntityManager entityManager;
  
      @SuppressWarnings("unchecked")
      public GUser findUser(String username){
          try{
  
              String login = "select * from guser where username=:username";
              Query result = entityManager.createNativeQuery(login,GUser.class)
                      .setParameter("username", username);
              List&lt;GUser&gt; list  = result.getResultList();
              System.out.println("size of user list : " + list.size());
              if (list.size() &gt; 0) {
                  GUser user_from_db = list.get(0);
                  return user_from_db;
              }
  
          }catch(DataAccessException e) {
              e.printStackTrace();
          }
          return null;
      }
  }
  </code></pre>
  
  <p>Is there any other code add for particular role like <code>anonymousUser</code> or <code>ROLE_ANONYMOUS</code> in my security java config class. I added <code>permitAll()</code> for <code>\login</code> related <code>URLS</code> . Or the spring security itself have any code for overcome this problem like I have a confusion . </p>