Search code examples
c#asp.net-coreauthorizationopeniddict

ASP.NET CORE 2.0 - [Authorize] doen't block the rest api access to unauthorized user


I am just learning a ASP.NET CORE. I have successfully implemented a openiddict to secure my api. After successful login user gets a token and that token is used for accessing web api but it is allowing unauthorized user too(i.e. the one who does't have token) This is how I have arranged by controller

namespace ISIA.Controllers
{
  [Authorize]
  [Route("api/[controller]")]
  public class PostController: Controller
  {
    private readonly IPostService _postService;
    private readonly PostToPostViewModelMapper _mapper;
    public PostController(
      IPostService postService
      )
    {
      _postService = postService;
      _mapper = new PostToPostViewModelMapper();
    }


    [HttpPost]
    public ObjectResult SavePost([FromBody] PostViewModel postViewModel)
    {
                 //method body
    }

    [HttpGet]
    public ObjectResult GetAllPost()
    {
       //method body  
    }
  }
}

in statup

 services.AddOpenIddict(options =>
      {
        options.AddEntityFrameworkCoreStores<ApplicationDbContext>();
        options.AddMvcBinders();
        options.EnableAuthorizationEndpoint("/connect/authorize")
                       .EnableLogoutEndpoint("/connect/logout")
                       .EnableTokenEndpoint("/connect/token")
                       .EnableUserinfoEndpoint("/api/userinfo");
        options.AllowAuthorizationCodeFlow();
        options.RequireClientIdentification();
        options.AllowPasswordFlow();
        options.AllowRefreshTokenFlow();
        options.DisableHttpsRequirement();
        options.UseRollingTokens(); //Uncomment to renew refresh tokens on every refreshToken request
                                    // options.AddSigningKey(new SymmetricSecurityKey(System.Text.Encoding.ASCII.GetBytes(Configuration["STSKey"])));
        options.Configure(
          config =>
          {
            // Enable sliding expiration
            config.UseSlidingExpiration = true;
            config.AccessTokenLifetime = TimeSpan.FromMinutes(240);
            config.RefreshTokenLifetime = TimeSpan.FromDays(15);
          });
      });

What I am doing wrong please help me out.


Solution

  • Set the AuthenticationSchemes in the Authorize attribute like this:

    [Authorize(AuthenticationSchemes = 
        OpenIddictValidationDefaults.AuthenticationScheme)]
    

    That will ensure the authorization is done with OAuth tokens not with Cookies.

    The OpenIddictValidationDefaults.AuthenticationScheme is defined here.

    Authorizing with a specific scheme is documented here.

    If that fails, which your comment suggests it did, then you also need to configure a token handler. That will look something like this:

    services
        .AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
        .AddJwtBearer(options => 
        {
            options.Audience = "https://localhost:5001/";
            options.Authority = "http://localhost:5000/";
        });