3

IF I login with correct username and password(as in my database),i am getting this error.

Error on Console(Browser)

: Failed to load http://localhost:8081/Documentprocess/api/users/login: Redirect from 'http://localhost:8081/Documentprocess/api/users/login' to 'http://localhost:8081/Documentprocess/api/users/login?error=true' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:4200' is therefore not allowed access.**

Login.html

<div class="container">
  <h1>Login</h1>
  <form [formGroup]="form" (ngSubmit)="signIN()">
    <div class="row">
     <div class="form-group col-lg-6">

    <div class="form-group" [ngClass]="{'has-error':!form.controls['userID'].valid && form.controls['userID'].touched}">
        <label>USER ID:</label>
        <input class="form-control" type="text" placeholder="John" [formControl]="form.controls['userID']"  [(ngModel)]="userID">
        <!-- The hasError method will tell us if a particular error exists -->

        <div *ngIf="form.controls['userID'].hasError('required') && form.controls['userID'].touched"
         class="alert alert-danger">Please Enter your USERID.</div>
    </div>

    <div class="form-group" [ngClass]="{'has-error':!form.controls['passWord'].valid && form.controls['passWord'].touched}">
        <label>PASSWORD:</label>
        <input class="form-control" type="password" [formControl]="form.controls['passWord']"  [(ngModel)]="passWord">
        <!-- The hasError method will tell us if a particular error exists -->

        <div *ngIf="form.controls['passWord'].hasError('required') && form.controls['passWord'].touched"
         class="alert alert-danger">Please Enter Your Password.</div>
    </div>

Login Component.ts

import { Component, OnInit } from '@angular/core';
import { Router, ActivatedRoute } from '@angular/router';
import {Login} from "./shared/login";
import { LoginService } from './shared/login.service'

//import { BasicValidators } from '../../shared/basic-validators';
import { FormBuilder, FormGroup, Validators, FormArray, FormControl } from '@angular/forms';
import {NgSelectModule} from '@ng-select/ng-select';
import { BrowserModule } from '@angular/platform-browser';


@Component({
  selector: 'app-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.css']
})
export class LoginComponent implements OnInit {
 private url: string = "http://localhost:8081/Documentprocess/api/users";
   form: FormGroup;
  title: string;
  userID: string;
  passWord: string;
  name:string;
  loading = false;
  error = '';
  searchForm: FormGroup;

  constructor(formBuilder: FormBuilder,
    private router: Router,
    private route: ActivatedRoute,
    private loginService: LoginService,
    ) {
    this.form = formBuilder.group({




  userID: ['', [  
      ]],
  passWord: ['', [         

      ]],



    });



 }

  ngOnInit() {
  }

  signIN() {

    var result,
        loginValue = this.form.value;

        result = this.loginService.login(this.userID,this.passWord);
        result.subscribe();

  }

  }

login.service.ts

import { Injectable } from '@angular/core';
import {Http, Response, Headers, RequestOptions} from "@angular/http";
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/do';
import 'rxjs/add/operator/catch';
import { Observable } from 'rxjs/Observable';
import {Login} from "./login";

@Injectable()
export class LoginService {

private url: string = "http://localhost:8081/Documentprocess/api/users";

constructor(private http: Http) { }

 login(userID: string ,passWord: string) {
    var headers = new Headers();
    headers.append('Content-Type', 'application/x-www-form-urlencoded');
    let options = new RequestOptions({ headers: headers });

  console.log(userID);
  console.log(passWord);
  console.log(this.url+'/login');
  return this.http.post(this.url+'/login', {username: userID,password: passWord}, options)
  .map(res => res.json());
 // console.log(user);

 }



}

Spring Security Configuration

package com.selfrespect.document.configuration;
import javax.sql.DataSource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;

@Configuration
@EnableWebSecurity
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {

    @Autowired
    private BCryptPasswordEncoder bCryptPasswordEncoder;

    @Autowired
    private DataSource datasource;


    @Value("${spring.queries.users-query}")
    private String usersQuery;

    @Value("${spring.queries.roles-query}")
    private String rolesQuery;

    @Override
    protected void configure(AuthenticationManagerBuilder auth)
            throws Exception {
        System.out.println(datasource);
        auth.
            jdbcAuthentication().dataSource(datasource)
                .usersByUsernameQuery("select userid,password from users where userid=?")
                .authoritiesByUsernameQuery("select role from users where userid=?");


    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        System.out.println("I am here");
        http.
            authorizeRequests()
                .antMatchers("/").permitAll()
                .antMatchers("/login").permitAll()
                .antMatchers("/api/services").permitAll()
                .antMatchers("/api/users/**").permitAll()
                .antMatchers("/admin/**").hasAuthority("ADMIN").anyRequest()
                .authenticated().and().csrf().disable().formLogin()
                .loginPage("/api/users/login").failureUrl("/api/users/login?error=true")
                .defaultSuccessUrl("/api/users/login_sucess")
                .usernameParameter("username")
                .passwordParameter("password")
                .and().logout()
                .logoutRequestMatcher(new AntPathRequestMatcher("/logout"))
                .logoutSuccessUrl("/").and().exceptionHandling()
                .accessDeniedPage("/access-denied");

    }

    @Override
    public void configure(WebSecurity web) throws Exception {
        web
           .ignoring()
           .antMatchers("/resources/**", "/static/**", "/css/**", "/js/**", "/images/**");
    }

}

MY SQL

0 Answers0