├── .gitignore
├── AuthBearer.xproj
├── Controllers
└── AccountController.cs
├── Dockerfile
├── Models
├── TokenAuthOptions.cs
└── User.cs
├── Properties
└── launchSettings.json
├── README.md
├── Startup.cs
├── appsettings.json
├── project.json
└── wwwroot
├── README.md
└── web.config
/.gitignore:
--------------------------------------------------------------------------------
1 |
2 | # Created by https://www.gitignore.io/api/visualstudio,visualstudiocode
3 |
4 | ### VisualStudio ###
5 | ## Ignore Visual Studio temporary files, build results, and
6 | ## files generated by popular Visual Studio add-ons.
7 |
8 | # User-specific files
9 | *.suo
10 | *.user
11 | *.userosscache
12 | *.sln.docstates
13 |
14 | # User-specific files (MonoDevelop/Xamarin Studio)
15 | *.userprefs
16 |
17 | # Build results
18 | [Dd]ebug/
19 | [Dd]ebugPublic/
20 | [Rr]elease/
21 | [Rr]eleases/
22 | x64/
23 | x86/
24 | bld/
25 | [Bb]in/
26 | [Oo]bj/
27 | [Ll]og/
28 |
29 | # Visual Studio 2015 cache/options directory
30 | .vs/
31 | # Uncomment if you have tasks that create the project's static files in wwwroot
32 | #wwwroot/
33 |
34 | # MSTest test Results
35 | [Tt]est[Rr]esult*/
36 | [Bb]uild[Ll]og.*
37 |
38 | # NUNIT
39 | *.VisualState.xml
40 | TestResult.xml
41 |
42 | # Build Results of an ATL Project
43 | [Dd]ebugPS/
44 | [Rr]eleasePS/
45 | dlldata.c
46 |
47 | # DNX
48 | project.lock.json
49 | artifacts/
50 |
51 | *_i.c
52 | *_p.c
53 | *_i.h
54 | *.ilk
55 | *.meta
56 | *.obj
57 | *.pch
58 | *.pdb
59 | *.pgc
60 | *.pgd
61 | *.rsp
62 | *.sbr
63 | *.tlb
64 | *.tli
65 | *.tlh
66 | *.tmp
67 | *.tmp_proj
68 | *.log
69 | *.vspscc
70 | *.vssscc
71 | .builds
72 | *.pidb
73 | *.svclog
74 | *.scc
75 |
76 | # Chutzpah Test files
77 | _Chutzpah*
78 |
79 | # Visual C++ cache files
80 | ipch/
81 | *.aps
82 | *.ncb
83 | *.opendb
84 | *.opensdf
85 | *.sdf
86 | *.cachefile
87 |
88 | # Visual Studio profiler
89 | *.psess
90 | *.vsp
91 | *.vspx
92 | *.sap
93 |
94 | # TFS 2012 Local Workspace
95 | $tf/
96 |
97 | # Guidance Automation Toolkit
98 | *.gpState
99 |
100 | # ReSharper is a .NET coding add-in
101 | _ReSharper*/
102 | *.[Rr]e[Ss]harper
103 | *.DotSettings.user
104 |
105 | # JustCode is a .NET coding add-in
106 | .JustCode
107 |
108 | # TeamCity is a build add-in
109 | _TeamCity*
110 |
111 | # DotCover is a Code Coverage Tool
112 | *.dotCover
113 |
114 | # NCrunch
115 | _NCrunch_*
116 | .*crunch*.local.xml
117 | nCrunchTemp_*
118 |
119 | # MightyMoose
120 | *.mm.*
121 | AutoTest.Net/
122 |
123 | # Web workbench (sass)
124 | .sass-cache/
125 |
126 | # Installshield output folder
127 | [Ee]xpress/
128 |
129 | # DocProject is a documentation generator add-in
130 | DocProject/buildhelp/
131 | DocProject/Help/*.HxT
132 | DocProject/Help/*.HxC
133 | DocProject/Help/*.hhc
134 | DocProject/Help/*.hhk
135 | DocProject/Help/*.hhp
136 | DocProject/Help/Html2
137 | DocProject/Help/html
138 |
139 | # Click-Once directory
140 | publish/
141 |
142 | # Publish Web Output
143 | *.[Pp]ublish.xml
144 | *.azurePubxml
145 | # TODO: Comment the next line if you want to checkin your web deploy settings
146 | # but database connection strings (with potential passwords) will be unencrypted
147 | *.pubxml
148 | *.publishproj
149 |
150 | # Microsoft Azure Web App publish settings. Comment the next line if you want to
151 | # checkin your Azure Web App publish settings, but sensitive information contained
152 | # in these scripts will be unencrypted
153 | PublishScripts/
154 |
155 | # NuGet Packages
156 | *.nupkg
157 | # The packages folder can be ignored because of Package Restore
158 | **/packages/*
159 | # except build/, which is used as an MSBuild target.
160 | !**/packages/build/
161 | # Uncomment if necessary however generally it will be regenerated when needed
162 | #!**/packages/repositories.config
163 | # NuGet v3's project.json files produces more ignoreable files
164 | *.nuget.props
165 | *.nuget.targets
166 |
167 | # Microsoft Azure Build Output
168 | csx/
169 | *.build.csdef
170 |
171 | # Microsoft Azure Emulator
172 | ecf/
173 | rcf/
174 |
175 | # Windows Store app package directories and files
176 | AppPackages/
177 | BundleArtifacts/
178 | Package.StoreAssociation.xml
179 | _pkginfo.txt
180 |
181 | # Visual Studio cache files
182 | # files ending in .cache can be ignored
183 | *.[Cc]ache
184 | # but keep track of directories ending in .cache
185 | !*.[Cc]ache/
186 |
187 | # Others
188 | ClientBin/
189 | ~$*
190 | *~
191 | *.dbmdl
192 | *.dbproj.schemaview
193 | *.pfx
194 | *.publishsettings
195 | node_modules/
196 | orleans.codegen.cs
197 |
198 | # Since there are multiple workflows, uncomment next line to ignore bower_components
199 | # (https://github.com/github/gitignore/pull/1529#issuecomment-104372622)
200 | #bower_components/
201 |
202 | # RIA/Silverlight projects
203 | Generated_Code/
204 |
205 | # Backup & report files from converting an old project file
206 | # to a newer Visual Studio version. Backup files are not needed,
207 | # because we have git ;-)
208 | _UpgradeReport_Files/
209 | Backup*/
210 | UpgradeLog*.XML
211 | UpgradeLog*.htm
212 |
213 | # SQL Server files
214 | *.mdf
215 | *.ldf
216 |
217 | # Business Intelligence projects
218 | *.rdl.data
219 | *.bim.layout
220 | *.bim_*.settings
221 |
222 | # Microsoft Fakes
223 | FakesAssemblies/
224 |
225 | # GhostDoc plugin setting file
226 | *.GhostDoc.xml
227 |
228 | # Node.js Tools for Visual Studio
229 | .ntvs_analysis.dat
230 |
231 | # Visual Studio 6 build log
232 | *.plg
233 |
234 | # Visual Studio 6 workspace options file
235 | *.opt
236 |
237 | # Visual Studio LightSwitch build output
238 | **/*.HTMLClient/GeneratedArtifacts
239 | **/*.DesktopClient/GeneratedArtifacts
240 | **/*.DesktopClient/ModelManifest.xml
241 | **/*.Server/GeneratedArtifacts
242 | **/*.Server/ModelManifest.xml
243 | _Pvt_Extensions
244 |
245 | # Paket dependency manager
246 | .paket/paket.exe
247 | paket-files/
248 |
249 | # FAKE - F# Make
250 | .fake/
251 |
252 | # JetBrains Rider
253 | .idea/
254 | *.sln.iml
255 |
256 |
257 | ### VisualStudioCode ###
258 | .vscode
259 |
260 |
--------------------------------------------------------------------------------
/AuthBearer.xproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | 14.0.24720
5 | $(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion)
6 |
7 |
8 |
9 | 9bd5574b-dfa6-47db-b77e-f5d1947ce91c
10 | AuthBearer
11 | ..\artifacts\obj\$(MSBuildProjectName)
12 | ..\artifacts\bin\$(MSBuildProjectName)\
13 |
14 |
15 |
16 | 2.0
17 |
18 |
19 |
--------------------------------------------------------------------------------
/Controllers/AccountController.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using Microsoft.AspNet.Mvc;
3 | using System.IdentityModel.Tokens.Jwt;
4 | using System.Security.Claims;
5 | using System.Security.Principal;
6 | using Microsoft.AspNet.Authorization;
7 | using AuthBearer.Models;
8 |
9 | namespace AuthBearer.Controllers
10 | {
11 | [Route("api/accounts")]
12 | public class AccountController : Controller
13 | {
14 | private readonly TokenAuthOptions _tokenOptions;
15 |
16 | public AccountController(TokenAuthOptions tokenOptions)
17 | {
18 | _tokenOptions = tokenOptions;
19 | }
20 |
21 | [AllowAnonymous]
22 | [HttpPost("login")]
23 | public dynamic Login([FromBody]User value)
24 | {
25 | //Defini uma data de expiração do Token
26 | var expires = DateTime.UtcNow.AddMinutes(5);
27 |
28 | //Cria uma instancia da classe que gera o token
29 | var handler = new JwtSecurityTokenHandler();
30 |
31 | //Criar as claims do usuário
32 | var identity = new ClaimsIdentity(new GenericIdentity(value.UserName, "TokenAuth"), new[] { new Claim("UserId", "1", ClaimValueTypes.Integer), new Claim(ClaimTypes.Role, "Admin") });
33 |
34 | // Gera as infos que iram constar token de segurança
35 | var securityToken = handler.CreateToken(
36 | issuer: _tokenOptions.Issuer,
37 | audience: _tokenOptions.Audience,
38 | signingCredentials: _tokenOptions.SigningCredentials,
39 | subject: identity,
40 | expires: expires);
41 |
42 | // Escreve o token de segurança
43 | var token = handler.WriteToken(securityToken);
44 |
45 | // retorna o token com as informações desejadas.
46 | return new { authenticated = true, entityId = 1, token = token, tokenExpires = expires };
47 |
48 | }
49 |
50 | [Authorize]
51 | [HttpGet]
52 | public string Get() => "Ok Authorized";
53 | }
54 | }
55 |
--------------------------------------------------------------------------------
/Dockerfile:
--------------------------------------------------------------------------------
1 | FROM microsoft/aspnet:1.0.0-rc1-update1
2 |
3 | RUN printf "deb http://ftp.us.debian.org/debian jessie main\n" >> /etc/apt/sources.list
4 | RUN apt-get -qq update && apt-get install -qqy sqlite3 libsqlite3-dev && rm -rf /var/lib/apt/lists/*
5 |
6 | COPY . /app
7 | WORKDIR /app
8 | RUN ["dnu", "restore"]
9 |
10 | EXPOSE 5000/tcp
11 | ENTRYPOINT ["dnx", "-p", "project.json", "web"]
12 |
--------------------------------------------------------------------------------
/Models/TokenAuthOptions.cs:
--------------------------------------------------------------------------------
1 | using System.IdentityModel.Tokens;
2 |
3 | namespace AuthBearer.Models
4 | {
5 | public class TokenAuthOptions
6 | {
7 | public string Issuer { get; set; }
8 | public string Audience { get; set; }
9 | public SigningCredentials SigningCredentials { get; set; }
10 | }
11 | }
12 |
--------------------------------------------------------------------------------
/Models/User.cs:
--------------------------------------------------------------------------------
1 | namespace AuthBearer.Models
2 | {
3 | public class User
4 | {
5 | public string Password { get; set; }
6 | public string UserName { get; set; }
7 | }
8 | }
9 |
--------------------------------------------------------------------------------
/Properties/launchSettings.json:
--------------------------------------------------------------------------------
1 | {
2 | "iisSettings": {
3 | "windowsAuthentication": false,
4 | "anonymousAuthentication": true,
5 | "iisExpress": {
6 | "applicationUrl": "http://localhost:3633/",
7 | "sslPort": 0
8 | }
9 | },
10 | "profiles": {
11 | "IIS Express": {
12 | "commandName": "IISExpress",
13 | "launchBrowser": true,
14 | "launchUrl": "api/values",
15 | "environmentVariables": {
16 | "ASPNET_ENV": "Development"
17 | }
18 | },
19 | "web": {
20 | "commandName": "web",
21 | "environmentVariables": {
22 | "Hosting:Environment": "Development"
23 | }
24 | }
25 | }
26 | }
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # Bearer Authentication com ASP.NET Core
2 |
3 | Esse projeto foi criado para demonstração de como realizar uma a implementação de autenticação utilizando Bearer Authentication no ASP.NET Core, para auxiliar o post que escrevi em meu blog pessoal [ntakashi.net]
4 |
5 | ### Pré requisitos
6 |
7 | É necessário ter instalado e configurado as seguintes tecnologias:
8 |
9 | * [ASP.NET Core]
10 | * [Yeoman]
11 | * [Generators ASP.NET]
12 | * [Visual Studio Code]
13 |
14 | ### Instação
15 |
16 | Precisamos ter todas as tecnologias do pré requisitos instaladas e configuradas
17 |
18 | ```sh
19 | $ git clone https://github.com/nicolastakashi/bearer-authentication-aspnet-core.git
20 | ```
21 |
22 | ```sh
23 | $ cd bearer-authentication-aspnet-core
24 | ```
25 | ```sh
26 | $ dnu restore
27 | ```
28 | ```sh
29 | $ dnu build
30 | ```
31 | ```sh
32 | $ dnx web
33 | ```
34 |
35 |
36 | [//]: # (These are reference links used in the body of this note and get stripped out when the markdown processor does its job. There is no need to format nicely because it shouldn't be seen. Thanks SO - http://stackoverflow.com/questions/4823468/store-comments-in-markdown-syntax)
37 |
38 |
39 | [Yeoman]:
40 | [ASP.NET Core]:
41 | [Generators ASP.NET]:
42 | [Visual Studio Code]:
43 | [ntakashi.net]:
44 |
45 |
--------------------------------------------------------------------------------
/Startup.cs:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/nicolastakashi/bearer-authentication-aspnet-core/cebeda906e63fd204f6e8a288978e609cd6b79d1/Startup.cs
--------------------------------------------------------------------------------
/appsettings.json:
--------------------------------------------------------------------------------
1 | {
2 | "Logging": {
3 | "IncludeScopes": false,
4 | "LogLevel": {
5 | "Default": "Verbose",
6 | "System": "Information",
7 | "Microsoft": "Information"
8 | }
9 | }
10 | }
11 |
--------------------------------------------------------------------------------
/project.json:
--------------------------------------------------------------------------------
1 | {
2 | "version": "1.0.0-*",
3 | "compilationOptions": {
4 | "emitEntryPoint": true
5 | },
6 | "tooling": {
7 | "defaultNamespace": "AuthBearer"
8 | },
9 |
10 | "dependencies": {
11 | "Microsoft.AspNet.IISPlatformHandler": "1.0.0-rc1-final",
12 | "Microsoft.AspNet.Mvc": "6.0.0-rc1-final",
13 | "Microsoft.AspNet.Server.Kestrel": "1.0.0-rc1-final",
14 | "Microsoft.AspNet.StaticFiles": "1.0.0-rc1-final",
15 | "Microsoft.Extensions.Configuration.FileProviderExtensions": "1.0.0-rc1-final",
16 | "Microsoft.Extensions.Logging": "1.0.0-rc1-final",
17 | "Microsoft.Extensions.Logging.Console": "1.0.0-rc1-final",
18 | "Microsoft.Extensions.Logging.Debug": "1.0.0-rc1-final",
19 | "Microsoft.AspNet.Authorization": "1.0.0-rc1-final",
20 | "Microsoft.AspNet.Authentication.JwtBearer": "1.0.0-rc1-final"
21 | },
22 |
23 | "commands": {
24 | "web": "Microsoft.AspNet.Server.Kestrel"
25 | },
26 |
27 | "frameworks": {
28 | "dnx451": { }
29 | },
30 |
31 | "exclude": [
32 | "wwwroot",
33 | "node_modules",
34 | "bower_components"
35 | ],
36 | "publishExclude": [
37 | "**.user",
38 | "**.vspscc"
39 | ]
40 | }
41 |
--------------------------------------------------------------------------------
/wwwroot/README.md:
--------------------------------------------------------------------------------
1 | # Welcome to ASP.NET 5
2 |
3 | We've made some big updates in this release, so it’s **important** that you spend a few minutes to learn what’s new.
4 |
5 | You've created a new ASP.NET 5 project. [Learn what's new](http://go.microsoft.com/fwlink/?LinkId=518016)
6 |
7 | ## This application consists of:
8 |
9 | * Sample pages using ASP.NET MVC 6
10 | * [Gulp](http://go.microsoft.com/fwlink/?LinkId=518007) and [Bower](http://go.microsoft.com/fwlink/?LinkId=518004) for managing client-side libraries
11 | * Theming using [Bootstrap](http://go.microsoft.com/fwlink/?LinkID=398939)
12 |
13 | ## How to
14 |
15 | * [Add a Controller and View](http://go.microsoft.com/fwlink/?LinkID=398600)
16 | * [Add an appsetting in config and access it in app.](http://go.microsoft.com/fwlink/?LinkID=699562)
17 | * [Manage User Secrets using Secret Manager.](http://go.microsoft.com/fwlink/?LinkId=699315)
18 | * [Use logging to log a message.](http://go.microsoft.com/fwlink/?LinkId=699316)
19 | * [Add packages using NuGet.](http://go.microsoft.com/fwlink/?LinkId=699317)
20 | * [Add client packages using Bower.](http://go.microsoft.com/fwlink/?LinkId=699318)
21 | * [Target development, staging or production environment.](http://go.microsoft.com/fwlink/?LinkId=699319)
22 |
23 | ## Overview
24 |
25 | * [Conceptual overview of what is ASP.NET 5](http://go.microsoft.com/fwlink/?LinkId=518008)
26 | * [Fundamentals of ASP.NET 5 such as Startup and middleware.](http://go.microsoft.com/fwlink/?LinkId=699320)
27 | * [Working with Data](http://go.microsoft.com/fwlink/?LinkId=398602)
28 | * [Security](http://go.microsoft.com/fwlink/?LinkId=398603)
29 | * [Client side development](http://go.microsoft.com/fwlink/?LinkID=699321)
30 | * [Develop on different platforms](http://go.microsoft.com/fwlink/?LinkID=699322)
31 | * [Read more on the documentation site](http://go.microsoft.com/fwlink/?LinkID=699323)
32 |
33 | ## Run & Deploy
34 |
35 | * [Run your app](http://go.microsoft.com/fwlink/?LinkID=517851)
36 | * [Run your app on .NET Core](http://go.microsoft.com/fwlink/?LinkID=517852)
37 | * [Run commands in your project.json](http://go.microsoft.com/fwlink/?LinkID=517853)
38 | * [Publish to Microsoft Azure Web Apps](http://go.microsoft.com/fwlink/?LinkID=398609)
39 |
40 | We would love to hear your [feedback](http://go.microsoft.com/fwlink/?LinkId=518015)
41 |
--------------------------------------------------------------------------------
/wwwroot/web.config:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
--------------------------------------------------------------------------------