Skip to content

Commit

Permalink
n2n/9 without refresh token
Browse files Browse the repository at this point in the history
  • Loading branch information
LICH010 committed Dec 11, 2017
1 parent 70ec6e1 commit a44e784
Show file tree
Hide file tree
Showing 36 changed files with 1,278 additions and 313 deletions.
12 changes: 7 additions & 5 deletions src/N2N.Api/Configuration/AppStart.cs
Original file line number Diff line number Diff line change
Expand Up @@ -43,14 +43,13 @@ internal static void UseMvcAndConfigureRoutes(IApplicationBuilder app)
/// <param name="container">DI container</param>
internal static void IntegrateSimpleInjector(IServiceCollection services, Container container)
{
container.Options.DefaultScopedLifestyle = new AspNetRequestLifestyle();
container.Options.DefaultScopedLifestyle = new AsyncScopedLifestyle();

services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();

services.AddSingleton<IControllerActivator>(
new SimpleInjectorControllerActivator(container));
services.AddSingleton<IViewComponentActivator>(
new SimpleInjectorViewComponentActivator(container));

services.AddSingleton<IControllerActivator>(new SimpleInjectorControllerActivator(container));
services.AddSingleton<IViewComponentActivator>(new SimpleInjectorViewComponentActivator(container));

services.EnableSimpleInjectorCrossWiring(container);
services.UseSimpleInjectorAspNetRequestScoping(container);
Expand All @@ -72,12 +71,15 @@ internal static void InitializeContainer(IApplicationBuilder app, Container cont
container.CrossWire<N2NDataContext>(app);
container.CrossWire<UserManager<N2NIdentityUser>>(app);
container.CrossWire<SignInManager<N2NIdentityUser>>(app);
container.CrossWire<IAuthentificationService>(app);

// Dependencies
container.Register<IRepository<N2NUser>, DbRepository<N2NUser>>();
container.Register<IRepository<N2NToken>, DbRepository<N2NToken>>();
container.Register<ISecurityService, SecurityService>();
container.Register<IN2NUserService, N2NUserService>();
container.Register<N2NApiUserService>();

}

internal static bool BootstrapDb(N2NDataContext ctx)
Expand Down
21 changes: 21 additions & 0 deletions src/N2N.Api/Configuration/TokenConfig.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.IdentityModel.Tokens;

namespace N2N.Api.Configuration
{
public class TokenConfig
{
public const string ISSUER = "MyAuthServer"; // издатель токена
public const string AUDIENCE = "*"; // потребитель токена
const string KEY = "mysupersecret_secretkey!123"; // ключ для шифрации
public const int LIFETIME = 60; // время жизни токена (180 минут рекомендуемое)
public static SymmetricSecurityKey GetSymmetricSecurityKey()
{
return new SymmetricSecurityKey(Encoding.ASCII.GetBytes(KEY));
}
}
}
54 changes: 46 additions & 8 deletions src/N2N.Api/Controllers/UserController.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,12 +3,15 @@
using System.Linq;
using System.Threading.Tasks;
using IdentityServer4.Extensions;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using N2N.Api.Filters;
using N2N.Api.Services;
using N2N.Core.Entities;
using N2N.Infrastructure.Models;
using Newtonsoft.Json;

namespace N2N.Api.Controllers
{
Expand All @@ -17,27 +20,55 @@ namespace N2N.Api.Controllers
public class UserController : Controller
{
private N2NApiUserService _apiUserService;
private IAuthentificationService _authentificationService;

public UserController(N2NApiUserService apiUserService)

public UserController(N2NApiUserService apiUserService, IAuthentificationService authentificationService)
{
this._authentificationService = authentificationService;
this._apiUserService = apiUserService;
}

[N2NAutorizationFilter]
[HttpGet("/user/СheckUser")]
public async Task<JsonResult> СheckUser()
{
var authHeader = HttpContext.Request.Headers["Authorization"];
string welcome_message ="Welcome "+_authentificationService.GetNameUser(authHeader.ToString());
return Json(welcome_message);
}

[HttpPost("/user/register")]
public async Task<IActionResult> Register([FromBody] UserDataForm userData)
public async Task<IActionResult> Register([FromBody] UserRegistrationFormDTO userRegistration)
{

if (!userData.NickName.IsNullOrEmpty() &&
!userData.Password.IsNullOrEmpty() &&
!userData.Capcha.IsNullOrEmpty() )
if (!userRegistration.NickName.IsNullOrEmpty() &&
!userRegistration.Password.IsNullOrEmpty() &&
!userRegistration.Capcha.IsNullOrEmpty() )
{
N2NUser user = new N2NUser() { NickName = userData.NickName };
var result = await this._apiUserService.CreateUserAsync(user, userData.Password);
N2NUser user = new N2NUser()
{
Id = Guid.NewGuid(),
NickName = userRegistration.NickName
};

var result = await this._apiUserService.CreateUserAsync(user, userRegistration.Password);

if (!result.Success)
{
return BadRequest(result.Messages);
}
return Ok(result.Messages);

var identity = await this._authentificationService.GetIdentity(userRegistration.NickName, userRegistration.Password);
if (identity == null)
{
Response.StatusCode = 400;
await Response.WriteAsync("Invalid username or password.");

}
var response = await this._authentificationService.GetTokenObject(identity, user.Id);

return Ok(response);
}
else
{
Expand All @@ -46,5 +77,12 @@ public async Task<IActionResult> Register([FromBody] UserDataForm userData)

}

[HttpDelete("/user/LogOut")]
public void LogOut()
{
var authHeader = HttpContext.Request.Headers["Authorization"];
this._authentificationService.DeleteToken(authHeader.ToString());
}

}
}
77 changes: 77 additions & 0 deletions src/N2N.Api/Filters/N2NAutorizationFilterAttribute.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Threading.Tasks;
using IdentityServer4.Extensions;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.ApplicationModels;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.Extensions.DependencyInjection;
using N2N.Api.Services;
using N2N.Infrastructure.Models;
using N2N.Services;

namespace N2N.Api.Filters
{
public class N2NAutorizationFilterAttribute : ActionFilterAttribute
{



public override void OnActionExecuting(ActionExecutingContext context)
{

var service = context.HttpContext.RequestServices.GetService<IAuthentificationService>();


ObjectResult result = new ObjectResult("");

var authHeader = context.HttpContext.Request.Headers["Authorization"];


if (authHeader.IsNullOrEmpty())
{
result = new ObjectResult("you do not have Authorization header");
result.StatusCode = 401;
}
else
{

var tokenValidationResult = service.ValidateTokenString(authHeader.ToString());

if (!tokenValidationResult.Success)
{
result = new ObjectResult(tokenValidationResult.Messages);
result.StatusCode = 401;
}
}

context.Result = result;
}

public override Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
{

return base.OnActionExecutionAsync(context, next);
}

public override void OnResultExecuted(ResultExecutedContext context)
{
base.OnResultExecuted(context);
}

public override void OnResultExecuting(ResultExecutingContext context)
{
base.OnResultExecuting(context);
}

public override Task OnResultExecutionAsync(ResultExecutingContext context, ResultExecutionDelegate next)
{
return base.OnResultExecutionAsync(context, next);
}


}
}
19 changes: 10 additions & 9 deletions src/N2N.Api/N2N.Api.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -7,15 +7,16 @@

<ItemGroup>
<PackageReference Include="IdentityServer4" Version="2.0.4" />
<PackageReference Include="Microsoft.AspNetCore" Version="2.0.0" />
<PackageReference Include="Microsoft.AspNetCore.Identity.EntityFrameworkCore" Version="2.0.0" />
<PackageReference Include="Microsoft.AspNetCore.Mvc" Version="2.0.0" />
<PackageReference Include="Microsoft.AspNetCore.StaticFiles" Version="2.0.0" />
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="2.0.0" />
<PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="2.0.0" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="2.0.0" />
<PackageReference Include="Microsoft.VisualStudio.Web.BrowserLink" Version="2.0.0" />
<PackageReference Include="Microsoft.VisualStudio.Web.CodeGeneration.Design" Version="2.0.0" />
<PackageReference Include="IdentityServer4.AccessTokenValidation" Version="2.1.0" />
<PackageReference Include="Microsoft.AspNetCore" Version="2.0.1" />
<PackageReference Include="Microsoft.AspNetCore.Identity.EntityFrameworkCore" Version="2.0.1" />
<PackageReference Include="Microsoft.AspNetCore.Mvc" Version="2.0.1" />
<PackageReference Include="Microsoft.AspNetCore.StaticFiles" Version="2.0.1" />
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="2.0.1" />
<PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="2.0.1" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="2.0.1" />
<PackageReference Include="Microsoft.VisualStudio.Web.BrowserLink" Version="2.0.1" />
<PackageReference Include="Microsoft.VisualStudio.Web.CodeGeneration.Design" Version="2.0.1" />
<PackageReference Include="SimpleInjector" Version="4.0.12" />
<PackageReference Include="SimpleInjector.Integration.AspNetCore" Version="4.0.12" />
<PackageReference Include="SimpleInjector.Integration.AspNetCore.Mvc" Version="4.0.12" />
Expand Down
Loading

0 comments on commit a44e784

Please sign in to comment.