Skip to content

Commit

Permalink
客户端登录
Browse files Browse the repository at this point in the history
  • Loading branch information
xiexingen committed Sep 23, 2019
1 parent 51f451f commit 94f6fe1
Show file tree
Hide file tree
Showing 22 changed files with 169 additions and 136 deletions.
54 changes: 54 additions & 0 deletions Core.Signalr.Template.Client/Controllers/AccountController.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
using Core.Signalr.Template.Client.Models;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Options;
using Microsoft.IdentityModel.Tokens;
using System;
using System.Collections.Generic;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;
using System.Threading.Tasks;

namespace Core.Signalr.Template.Client.Controllers
{
public class AccountController : Controller
{
[HttpGet]
[AllowAnonymous]
public IActionResult Login()
{
if (User.Identity.IsAuthenticated)
{
return RedirectToAction("Index", "Home");
}
return View();
}

[HttpPost]
[AllowAnonymous]
public async Task<IActionResult> Login(string userName)
{
if (string.IsNullOrWhiteSpace(userName))
{
throw new Exception("用户名不能为空");
}

var claims = new List<Claim>() {
new Claim(ClaimTypes.Name,userName),
};
var claimIdentity = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme);
await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, new ClaimsPrincipal(claimIdentity));

return RedirectToAction("Index","Home");
}

public async Task<IActionResult> LoginOut()
{
await HttpContext.SignOutAsync();
return RedirectToAction(nameof(AccountController.Login), "Account");
}
}
}
13 changes: 13 additions & 0 deletions Core.Signalr.Template.Client/Controllers/HomeController.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;

namespace Core.Signalr.Template.Client.Controllers
{
public class HomeController : Controller
{
public IActionResult Index()
{
return View();
}
}
}
11 changes: 7 additions & 4 deletions Core.Signalr.Template.Client/Core.Signalr.Template.Client.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -7,12 +7,15 @@
<StartupObject />
</PropertyGroup>

<ItemGroup>
<Folder Include="Controllers\" />
</ItemGroup>

<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="3.0.0-rc1.19457.4" />
<PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="3.0.0-rc1.19456.14" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="3.0.0-rc1.19456.14">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="Microsoft.Extensions.Logging.Debug" Version="3.0.0-rc1.19456.10" />
<PackageReference Include="Microsoft.VisualStudio.Web.CodeGeneration.Design" Version="3.0.0-rc1-19462-10" />
</ItemGroup>


Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="Current" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup>
<Controller_SelectedScaffolderID>MvcControllerEmptyScaffolder</Controller_SelectedScaffolderID>
<Controller_SelectedScaffolderCategoryPath>root/Controller</Controller_SelectedScaffolderCategoryPath>
<WebStackScaffolding_ControllerDialogWidth>600</WebStackScaffolding_ControllerDialogWidth>
<WebStackScaffolding_IsLayoutPageSelected>True</WebStackScaffolding_IsLayoutPageSelected>
<WebStackScaffolding_IsPartialViewSelected>False</WebStackScaffolding_IsPartialViewSelected>
<WebStackScaffolding_IsReferencingScriptLibrariesSelected>True</WebStackScaffolding_IsReferencingScriptLibrariesSelected>
<WebStackScaffolding_LayoutPageFile />
<WebStackScaffolding_IsAsyncSelected>False</WebStackScaffolding_IsAsyncSelected>
</PropertyGroup>
</Project>
26 changes: 0 additions & 26 deletions Core.Signalr.Template.Client/Pages/Error.cshtml

This file was deleted.

23 changes: 0 additions & 23 deletions Core.Signalr.Template.Client/Pages/Error.cshtml.cs

This file was deleted.

17 changes: 0 additions & 17 deletions Core.Signalr.Template.Client/Pages/Index.cshtml.cs

This file was deleted.

8 changes: 0 additions & 8 deletions Core.Signalr.Template.Client/Pages/Privacy.cshtml

This file was deleted.

16 changes: 0 additions & 16 deletions Core.Signalr.Template.Client/Pages/Privacy.cshtml.cs

This file was deleted.

5 changes: 5 additions & 0 deletions Core.Signalr.Template.Client/Program.cs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;

namespace Core.Signalr.Template.Client
{
Expand All @@ -12,6 +13,10 @@ public static void Main(string[] args)

public static IHostBuilder CreateWebHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureLogging(logging =>
{
logging.AddConsole();
})
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
Expand Down
21 changes: 15 additions & 6 deletions Core.Signalr.Template.Client/Startup.cs
Original file line number Diff line number Diff line change
@@ -1,12 +1,15 @@
using Core.Signalr.Template.Client.Models;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Authorization;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using System;

namespace Core.Signalr.Template.Client
{
Expand All @@ -30,14 +33,20 @@ public void ConfigureServices(IServiceCollection services)

// services.AddHostedService<ClearBackGroundService>();

services.AddAuthentication(options =>
services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
.AddCookie(CookieAuthenticationDefaults.AuthenticationScheme, cookieOption =>
{
cookieOption.LoginPath = "/Account/Login";
cookieOption.AccessDeniedPath = "/Account/Login";
});

services.Configure<CookiePolicyOptions>(options =>
{
options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultForbidScheme = JwtBearerDefaults.AuthenticationScheme;
options.CheckConsentNeeded = context => true;
options.MinimumSameSitePolicy = SameSiteMode.None;
});

services.AddMvc()
services.AddMvc(options => options.Filters.Add(new AuthorizeFilter()))
.SetCompatibilityVersion(CompatibilityVersion.Version_3_0);
}

Expand All @@ -59,7 +68,7 @@ public void Configure(IApplicationBuilder app)

app.UseAuthentication();
app.UseAuthorization();

app.UseRouting();

app.UseEndpoints(endpoints =>
Expand Down
23 changes: 23 additions & 0 deletions Core.Signalr.Template.Client/Views/Account/Login.cshtml
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
@{
ViewData["Title"] = "Signalr 登录";
}

<div id="pageContent">
<div class="card">
<div class="card-header">
<div class="card-title">登录</div>
</div>
<div class="card-body">
<form method="post" action="/Account/Login">
<div class="form-group">
<label for="userName">用户名</label>
<input autocomplete="off" type="text" class="form-control" name="userName" placeholder="用户名">
</div>
<button type="submit" class="btn btn-primary">假装登录</button>
</form>
</div>
</div>
</div>
@section Scripts{

}
Original file line number Diff line number Diff line change
@@ -1,6 +1,4 @@
@page
@model IndexModel
@{
@{
ViewData["Title"] = "Signalr Demo";
}

Expand Down Expand Up @@ -36,7 +34,9 @@
<div class="col-sm-8">
<div class="card">
<div class="card-header">
<div class="card-title">当前用户:{{userInfo.userName}},加入的组:{{userInfo.groups}}</div>
<div class="card-title">
当前用户:{{userInfo.userName}} - 加入的组:{{userInfo.groups}} - 连接Id:{{userInfo.connectionId}}
</div>
</div>
<textarea id="logs" rows="20" class="form-control">{{logs.join('\r\n')}}</textarea>
</div>
Expand All @@ -47,14 +47,10 @@
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLabel">请输入。。。</h5>
<h5 class="modal-title" id="exampleModalLabel">请输入连接的组</h5>
</div>
<div class="modal-body">
<form id="formInfo">
<div class="form-group">
<label for="recipient-name" class="col-form-label">用户名:</label>
<input type="text" autocomplete="off" required class="form-control" id="userName">
</div>
<div class="form-group">
<label for="message-text" class="col-form-label">组:</label>
<textarea autocomplete="off" placeholder="多个以,隔开" required class="form-control" id="groups"></textarea>
Expand All @@ -78,8 +74,9 @@
data: {
// 用户信息
userInfo: {
userName: '',
groups: ''
userName: '@User.Identity.Name',
groups: '',
connectId:''
},
// 日志
logs: [],
Expand All @@ -100,8 +97,8 @@
},
mounted: function () {
// initConnect();
testInitConnect();
initConnect();
//testInitConnect();
}
})
Expand Down Expand Up @@ -129,28 +126,22 @@
})
$('#collectionUserInfo').on('hidden.bs.modal', function (event) {
var modal = $(this);
var userName = $("#userName").val();
var groups = $("#groups").val();
if (!userName || !groups) {
modal.modal('show');
return;
}
initSignalr({
// var modal = $(this);
var groups = $("#groups").val()||'';
var connect=initSignalr({
delay: 0,
url: 'http://localhost:50001/notify-hub?userId=' + userName + '&group=' + groups,
url: 'http://localhost:50001/notify-hub?userId=' + vm.userInfo.userName + '&group=' + groups,
loggingLevel: signalR.LogLevel.Error,
onNotify: function (data) {
$logs.val($logs.val() + '\r\nOnNotify..........' + JSON.stringify(data));
},
onStarted: function () {
vm.$set(vm.userInfo, 'userName', userName);
vm.$set(vm.userInfo, 'connectionId', connect.connectionId);
vm.$set(vm.userInfo, 'groups', groups);
vm.logs.push('连接成功');
}
});
})
}
})
</script>
Expand Down
Loading

0 comments on commit 94f6fe1

Please sign in to comment.