· 7 years ago · Dec 15, 2018, 07:54 AM
1
2using System;
3using System.Collections.Generic;
4using System.IdentityModel.Tokens.Jwt;
5using System.Security.Claims;
6using System.Text;
7using Microsoft.AspNetCore.Mvc;
8using Microsoft.IdentityModel.Tokens;
9using TimeRegister.Models;
10
11// For more information on enabling Web API for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860
12
13namespace TimeRegister.Controllers
14{
15 [Route("api/auth")]
16 public class AuthController : Controller
17 {
18 // GET api/values
19 [HttpPost, Route("login")]
20 public IActionResult Login([FromBody]LoginModel user)
21 {
22 if (user == null)
23 {
24 return BadRequest("Invalid client request");
25 }
26
27 if (user.UserName == "johndoe" && user.Password == "def@123")
28 {
29 var secretKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("superSecretKey@345"));
30
31 var signinCredentials = new SigningCredentials(secretKey, SecurityAlgorithms.HmacSha256);
32
33 var tokeOptions = new JwtSecurityToken(
34 issuer: "http://localhost:44305",
35 audience: "http://localhost:44305",
36 claims: new List<Claim>(),
37 expires: DateTime.Now.AddMinutes(50),
38 signingCredentials: signinCredentials
39 );
40
41 var tokenString = new JwtSecurityTokenHandler().WriteToken(tokeOptions);
42 return Ok(new { Token = tokenString });
43 }
44 else
45 {
46 return Unauthorized();
47 }
48 }
49 }
50}